【问题标题】:"php://input" returning string for json ajax requestjson ajax 请求的“php://input”返回字符串
【发布时间】:2017-05-31 18:09:00
【问题描述】:

我从file_get_contents('php://input') 得到一个字符串。我试过json_decode(),但字符串不是json。这是ajax请求和php代码。如何获取ajax请求发送的json并将其转换为php数组?

$data = file_get_contents('php://input');
var_dump($data);
echo $data;

输出:

string(7) "id=myId"
"id=myId"

Ajax(包括 Jquery):

$.ajax({
    "url": "myFile.php",
    "type": "POST",
    "contentType": "Json",
    "data": {"id": "myId"},
}).done(function(data, status) {
    if (status == "success") {
        console.log(data);
    }
}).fail(function(data, status, error) {
    throw new Error(error);
    console.log(data);
    console.log(status);
});

编辑:json_encode() 返回 null,所以我不能使用这个问题的答案:PHP: file_get_contents('php://input') returning string for JSON message

【问题讨论】:

标签: javascript php jquery json ajax


【解决方案1】:

就像 Sammitch 在他的评论中提到的那样,您当前的代码使用表单编码发送它。对于您想要的,在将数据发送到服务器之前对数据进行字符串化,以便将其作为 JSON 接收。修改你的调用如下:

$.ajax({
    "url": "myFile.php",
    "type": "POST",
    "contentType": "application/json",
    "data": JSON.stringify({"id": "myId"}),
})

这应该导致输入是一个 json 编码的对象。

【讨论】:

  • 看来我的问题出在客户端,而不是服务器端。现在完成此操作后,json_encode() 正在工作!
猜你喜欢
  • 1970-01-01
  • 2015-06-14
  • 2014-03-25
  • 1970-01-01
  • 1970-01-01
  • 2015-01-24
  • 1970-01-01
  • 2013-04-23
  • 2023-04-09
相关资源
最近更新 更多