我从 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'(返回JSON消息的字符串
就像sammitch在他的评论中提到的那样,您当前的代码正在用表单编码发送。对于您想要的内容,请在将数据发送到服务器之前将其串起,以便将其作为JSON接收到。修改您的电话以这样:
$.ajax({
"url": "myFile.php",
"type": "POST",
"contentType": "application/json",
"data": JSON.stringify({"id": "myId"}),
})
这应该导致输入是JSON编码对象。