【问题标题】:jQuery AJAX POST data not getting to PHP [duplicate]jQuery AJAX POST数据没有进入PHP [重复]
【发布时间】:2018-08-07 15:48:27
【问题描述】:

我有一个 AJAX 调用,它没有从 data 参数向服务器发送信息。我用下面的 PHP 代码确认它被识别为 POST 请求。您会注意到我的var_dump($_POST) 不包含“myData”数据。我不知道从这里去哪里。

JavaScript

$.ajax({
    method : 'POST',
    contentType: 'application/json; charset=utf-8',
    url : myURL,    
    data : {
        'myData' : 'myData'
    },  
    async : true,
    success: function (results) {
    console.log('here are the results: ' + results);
},
error: function (req, msg, obj) {
  console.log('An error occured while executing a request');
  console.log('Error: ' + msg);
}
});

PHP

if ($_SERVER["REQUEST_METHOD"] == "POST") { 
echo var_dump($_POST);
}

控制台日志

here are the results: array(1) { ["phpURI"]=> unicode(33) "php/main.php?
function=myFunction" } 

谢谢!

【问题讨论】:

  • $_POST 仅当内容类型请求标头指示“multipart/form-data”或“application/x-www-form-urlencoded”请求时才会自动填充。对于任何其他内容类型,您需要自己解析原始输入数据。

标签: php jquery ajax post


【解决方案1】:

由于Content-Type: application/json; charset=utf-8 标头,您的 AJAX 请求正在发布 JSON 数据。

如果您只是删除该行,$.ajax 默认为 application/x-www-form-urlencoded; charset=UTF-8,这会导致 PHP 将其作为键值对放入 $_POST

【讨论】:

    猜你喜欢
    • 2016-05-26
    • 2022-08-04
    • 1970-01-01
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-27
    • 1970-01-01
    相关资源
    最近更新 更多