PHP 无法识别 JSON 发布消息


php does not recognize JSON post message

我正在努力通过XMLhttp post请求发送JSON数据。数据是:

"{"reqData":{"reqType":"post","reqName":"getCurrTemp","reqPayload":""}}"

JS代码是:

       var reqData  =  { 
            reqType : "post", //isDateRequested : 1,
            reqName : "getCurrTemp",
            reqPayload : "" 
        };
        var dataToSend = {'reqData' : reqData };
        var jData = JSON.stringify(dataToSend);
        alert(jData);
        var oReq = new XMLHttpRequest(); 
            oReq.onload = function() {
            data = JSON.parse(this.responseText);
            };
            oReq.open("POST", "handleRequests.php", true);
        oReq.send(jData);

我在 php 方面遇到了问题,看起来服务器无法识别 JSON,甚至消息丢失......

我用wireshark嗅探流量:

POST /autHouse/handleRequests.php HTTP/1.1
Host: 192.168.0.12
Connection: keep-alive
Content-Length: 70
Origin: http://192.168.0.12
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36
Content-Type: text/plain;charset=UTF-8
Accept: */*
Referer: http://192.168.0.12/autHouse/ah.html
Accept-Encoding: gzip, deflate
Accept-Language: pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4
{"reqData":{"reqType":"post","reqName":"getCurrTemp","reqPayload":""}}HTTP/1.1 200 OK
Date: Tue, 19 Jan 2016 10:53:22 GMT
Server: Apache/2.2.22 (Debian)
X-Powered-By: PHP/5.4.45-0+deb7u2
Content-Length: 84
Keep-Alive: timeout=5, max=99
Connection: Keep-Alive
Content-Type: text/html
string(70) "{"reqData":{"reqType":"post","reqName":"getCurrTemp","reqPayload":""}}"

这是PHP代码:

    $body = file_get_contents('php://input');
    error_log(var_dump($body));
    $reqData= json_decode($_POST['reqData'], true);
    $reqType = $reqData["reqType"];
    $reqName = $reqData["reqName"];

并实现PHP错误日志:

[Tue Jan 19 11:54:23 2016] [error] [client 192.168.0.121] , referer: http://192.168.0.12/autHouse/ah.html
[Tue Jan 19 11:54:23 2016] [error] [client 192.168.0.121] PHP Notice:  Undefined index: reqData in /var/www/autHouse/handleRequests.php on line 15, referer: http://192.168.0.12/autHouse/ah.html

你能告诉我为什么 php 在发送正确的 JSON 数据时

符合吗?

问候J.

试试这个

var xmlhttp = new XMLHttpRequest(); 
xmlhttp.open("POST", "handleRequests.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(jData);

您错过了结果数组中的一个级别。

$body = file_get_contents('php://input');
error_log(var_dump($body));
$reqData= json_decode($_POST['reqData'], true);
$reqType = $reqData['reqData']["reqType"];
$reqName = $reqData['reqData']["reqName"];

如果您更喜欢使用传递数据的对象而不是将对象转换为数组,您可以这样做

$body = file_get_contents('php://input');
error_log(var_dump($body));
$reqData= json_decode($_POST['reqData']);
$reqType = $reqData->reqData->reqType;
$reqName = $reqData->reqData->reqName;