PHP不会使用FormData从AJAX接收POST数据

时间:2018-03-20 16:20:13

标签: php jquery ajax post form-data

我正在尝试使用JavaScript和PHP传递一些基本数据。

PHP没有收到任何数据。

我有以下JavaScript代码:

var formData = new FormData();

formData.append("action", "save-game");
formData.append("title", title);
formData.append("players", players);
formData.append("noTables", noTables);
formData.append("maxPPT", maxPPT);
formData.append("rounds", roundChart);

$.ajax({
    url: "/static/apps/games.php",
    type: "POST",
    data: formData,
    processData: false,
    contentType: false,
    success: function(response){
        if (response.success) {
            alert("Saved Game Setup");
        } else {
            alert("Failed to save game setup, "+response.reason);
            console.log(response.reason);
        }
    }
})

我已经将PHP剥离到最低限度,但它仍然没有收到数据

header("Content-Type: application/json");

$action = $_POST["action"];

echo json_encode(array(
    'success' => false,
    'reason' => $action,
));

PHP中的$action变量返回null

1 个答案:

答案 0 :(得分:0)

尝试像这里一样构建数据



var buildData = function( _action, _title, _players, _noTables, _maxPPT, _rounds){
  var data = {};
  data.action = _action;
  data.title = _title;
  data.players = _players;
  data.noTables = _noTables;
  data.maxPPT = _maxPPT;
  data.rounds = _rounds;

  return JSON.stringify(data);
}

var _json = buildData("save-game", title, players, noTables, maxPPT, roundChart);