2016-01-19 128 views
1

Im正在努力通過XMLhttp發送請求發送JSON數據。 數據是:php無法識別JSON發佈消息

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

JS代碼是:在PHP端有問題

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

IM,看起來像服務器無法識別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"]; 

和realted 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 complians而IM發送正確的JSON數據?

認爲 J.

+1

試試這個'$ reqData = json_decode($身體,真); ' – RiggsFolly

+0

沒有改變一件事... – JosiP

回答

0

試試這個

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

仍然同樣reslut ... – JosiP

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"]; 

如果您更喜歡使用的數據正在傳遞的對象爲,而不是轉換對象數組,你可以做

​​
相關問題