【问题标题】:PHP wont receive POST data from AJAX using FormDataPHP 不会使用 FormData 从 AJAX 接收 POST 数据
【发布时间】:2018-03-20 16:20:12
【问题描述】:

我正在尝试使用 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

【问题讨论】:

  • 这可能是您的 javascript 端的控制台错误。去看看:)
  • PHP 是否理解这样的请求,取决于 Content-Type 标头。你出于某种原因决定指示 jQuery 根本不发送,所以这当然失败了。
  • 您使用的是什么版本的 jQuery?检查控制台和网络选项卡也是诊断问题的良好开端。
  • "仍然告诉我请求方法是 GET" - 你确定你正在查看以 ... 开头的正确代码部分吗?该 GET 请求是唯一显示在网络面板中的请求......可能不是直接在它之前的 POST,它会获得重定向响应或类似的东西?
  • 你有这个在线我们可以看看的地方吗?

标签: php jquery ajax post form-data


【解决方案1】:

尝试像这里一样构建数据

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-02
    • 2020-09-13
    • 2022-12-13
    • 1970-01-01
    相关资源
    最近更新 更多