" php://input"返回json ajax请求的字符串 [英] "php://input" returning string for json ajax request

查看:99
本文介绍了" php://input"返回json ajax请求的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;

输出:

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

Ajax(包括Jquery):

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);
});

json_encode()返回null,所以我不能使用以下问题的答案:

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

推荐答案

就像Sammitch在他的评论中提到的那样,您当前的代码正在使用表单编码发送它.对于所需的数据,在将数据发送到服务器之前对其进行字符串化,以便将其作为JSON接收.修改您的通话,使其像这样:

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"}),
})

这应该导致输入是json编码的对象.

This should result in the input being a json encoded object.

这篇关于" php://input"返回json ajax请求的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆