php无法识别JSON帖子消息

时间:2016-01-19 11:06:14

标签: php json

我正在努力通过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

在发送正确的JSON数据时,能否告诉我为什么php complians?

问候 学家

2 个答案:

答案 0 :(得分:1)

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

$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;

答案 1 :(得分:0)

试试这个

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