简体   繁体   English

“php:// input”为json ajax请求返回字符串

[英]“php://input” returning string for json ajax request

I am getting a string from file_get_contents('php://input') . 我从file_get_contents('php://input')获取一个字符串。 I tried json_decode() , but the string is not a json. 我试过json_decode() ,但字符串不是json。 Here is the ajax request and the php code. 这是ajax请求和php代码。 How can I get the json sent from the ajax request and turn it into a php array? 如何从ajax请求中获取json并将其转换为php数组?

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

Output: 输出:

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

Ajax(Includes Jquery): 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);
});

Edit: json_encode() is returning null, so I cannot use the answer from this question: PHP: file_get_contents('php://input') returning string for JSON message 编辑: json_encode()返回null,所以我不能使用这个问题的答案: PHP:file_get_contents('php:// input')返回JSON消息的字符串

Like Sammitch mentioned in his comment, your current code is sending it with form encoding. 就像Sammitch在评论中提到的那样,您当前的代码是使用表单编码发送它。 For what you want, stringify the data before sending it to the server, so that it gets received as JSON. 根据需要,在将数据发送到服务器之前对其进行字符串化,以便将其作为JSON接收。 Modify your call to be like this: 将您的通话修改为:

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

This should result in the input being a json encoded object. 这应该导致输入是json编码对象。

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

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