我从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
答案 0 :(得分:3)
就像Sammitch在评论中提到的那样,您当前的代码是使用表单编码发送的。根据需要,在将数据发送到服务器之前对其进行字符串化,以便将其作为JSON接收。将您的通话修改为:
$.ajax({
"url": "myFile.php",
"type": "POST",
"contentType": "application/json",
"data": JSON.stringify({"id": "myId"}),
})
这应该导致输入是json编码对象。