douqiao8370
2017-05-31 18:09
浏览 190

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

I am getting a string from file_get_contents('php://input'). I tried json_decode(), but the string is not a json. Here is the ajax request and the php code. How can I get the json sent from the ajax request and turn it into a php array?

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

Output:

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

Ajax(Includes 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

图片转代码服务由CSDN问答提供 功能建议

我从 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”},
 完成(函数(数据,状态){
 if(status ==“success”){
 console.log(data); 
} 
})。失败(函数(数据,状态,错误)  ){
 throw new Error(error); 
 console.log(data); 
 console.log(status); 
}); 
   
 
 

编辑: json_encode()返回null,所以我不能使用这个问题的答案: PHP:file_get_contents('php:// input')返回JSON消息的字符串

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dousong5492 2017-05-31 18:12
    已采纳

    Like Sammitch mentioned in his comment, your current code is sending it with form encoding. For what you want, stringify the data before sending it to the server, so that it gets received as 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.

    点赞 评论

相关推荐 更多相似问题