繁体   English   中英

jQuery ajax发布:PHP没内容

[英]jQuery ajax post: PHP get's no content

我很想问,但是到目前为止我还没有找到任何解决方案。 我一直以为,这可能只是一个愚蠢的错误,但我找不到。

我有一个jQuery 2.1 ajax POST到我的PHP服务器:

$.ajax({
  url: "http://my-server.com/post-example.php",
  type: 'POST',
  contentType: 'application/json; charset=utf-8',
  dataType: 'json',
  data: JSON.stringify({ foo: "bar" }),
  success: function(data) {
    console.log("SUCCESS");
  },
});

Safari在控制台中告诉我,请求数据正确且已发送。 尝试在PHP中访问foo ,所有内容均为空:

var_dump($_POST); // array(0)
$foo = file_get_contents("php://input");
var_dump($foo); // string(0)

当我尝试使用curl进行POST时,我在php://input得到结果:

curl -v -X POST -H "Content-Type: application/json" -d '{"foot":"bar"}' http://www.my-server.de/post-example.php

// on PHP side
var_dump($_POST); // array(0)
$foo = file_get_contents("php://input");
var_dump($foo); // string(13) "{"foo":"bar"}"

我找不到原因。 也许我的PHP配置有问题,但是我已经在php.ini设置了always_populate_raw_post_data = On

我也试过没有contentTypedataType ,效果相同。

您正在发送字符串而不是JSON,请像这样修复它:

 $.ajax({
     url: "res.php",
     type: "POST",
     data: { foo: "bar" },
     success: function(result) {
        console.log(result);
     }
 });

print_r($_POST)返回以下内容:

Array
(
    [foo] => bar
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM