【问题标题】:jQuery ajax post: PHP get's no contentjQuery ajax 帖子:PHP 没有内容
【发布时间】:2014-02-14 12:36:22
【问题描述】:

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

我有一个 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,效果一样。

【问题讨论】:

  • 不是同一个问题? stackoverflow.com/questions/298745/…
  • 很遗憾没有。我可以到达服务器,并且我得到了每个输出,但是来自 PHP 的请求变量是空的。
  • 嗯,为什么要字符串化?您可以只发布数据:{ foo: "bar" },但不知道它是否会有所作为。
  • 我试过没有stringify,结果一样

标签: javascript php jquery ajax curl


【解决方案1】:

你发送的是字符串而不是 JSON,像这样修复它:

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

print_r($_POST) 回复了这个:

Array
(
    [foo] => bar
)

【讨论】:

  • 感谢您的回答。我在没有dataType 和有无stringify 的情况下尝试了它。不幸的是,在查看file_get_contents("php://input") 时,我仍然没有在 PHP 中得到任何结果。还有其他想法吗?
猜你喜欢
  • 1970-01-01
  • 2015-03-25
  • 2013-04-27
  • 1970-01-01
  • 2015-01-05
  • 1970-01-01
  • 2014-04-26
  • 2014-09-20
  • 1970-01-01
相关资源
最近更新 更多