這的jQuery代碼工作:的jQuery JavaScript的主場迎戰阿賈克斯POST「功能
$.ajax({
type: "POST",
url: "file.php",
data: { json: json },
complete: function (data) {
var result = data.responseText;
console.log(result); // logs 'echo' from PHP file
}
});
這的JavaScript代碼仍然不工作:
var xhr = new XMLHttpRequest();
xhr.open("POST", "file.php", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var result = xhr.responseText;
console.log(result); // supposed to log 'echo' from PHP file
}
}
xhr.send(JSON.stringify(json));
是不是這兩種方法相當於,還是我錯過了什麼?
假設 'file.php' 看起來是這樣的:
if(isset($_POST['json'])){
$obj = json_decode($_POST['json']);
//some php operation
// echo $obj keys and values
}
必須調用打開後setRequestHeader()()https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest – Nitin
請求頭可能是錯誤的(可能是'應用程序/ json'),但我很確定你必須stringify你的json:'xmlHttp.send(JSON.stringify(json));' – Will
@很好,我敢打賭,我需要這樣做,但沒有修理它。 – Wagtail