2016-12-02 45 views
0

我有JavaScript代碼將數據發送到PHP。AJAX數據未到PHP

爲什麼我無法獲取JSON數據?

xhr = new XMLHttpRequest(); 
var url = "http://192.168.1.4/temp.php"; 
xhr.open("POST", url, true); 
xhr.setRequestHeader("Content-type", "application/json"); 
xhr.onreadystatechange = function() { 
    if (xhr.readyState == 4 && xhr.status == 200) { 
     var json = JSON.parse(xhr.responseText); 

    } 
} 

var aa = [{ 
    "email": "[email protected]", 
    "password": "101010" 
}, { 
    email: '[email protected]', 
    "passqword": "112" 
}]; 
xhr.send(aa); 

我創造這樣的PHP代碼來獲取數據:

<?php 
    header('Access-Control-Allow-Origin: *'); 
    header("Content-Type: application/json"); 
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept"); 
    $v = json_decode(stripslashes(file_get_contents("php://input"))); 
    echo $v; 
?> 
+0

閱讀['__POST'](http://php.net/manual/en/reserved.variables.post.php) –

+0

沒有關於json數據 – kohli

+0

什麼顯示在控制檯中? – Jaber

回答

1

stripslashes極有可能突破您所提交(雖然在這個例子中給出的特定輸入的JSON,它根本沒有效果,沒有斜槓)。

更重要的是,返回值json_decode是一個PHP數組。該函數預計JSON爲輸入

當你迴應$v時,你有一個PHP數組而不是JSON。

由於您輸出的不是JSON,因此JSON.parse(xhr.responseText);將會失敗。