有許多事情錯了你的請求。您可以使用’ t POST數據,而不使用application/x-www-form-urlencoded
。其次,「 Hello World! 」不會被轉義或附加到變量。
以下是將數據發送到服務器的JavaScript代碼。
var xhr = new XMLHttpRequest();
var params = 'x='+encodeURIComponent("Hello World!");
xhr.open("POST", 'example.php', true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", params.length);
xhr.setRequestHeader("Connection", "close");
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
xhr.send(params);
您可以通過PHP中的$_POST['x']
訪問此項。
或者,您可以使用$_GET['x']
通過使用下面的代碼。
var xhr = new XMLHttpRequest();
var params = encodeURIComponent("Hello World!");
xhr.open("GET", 'example.php?x='+params, true);
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
xhr.send(null);
GET更符合使用Content-type: text/plain
的想法。
這是我想知道的所有:)謝謝 – abc
@genkidesu:我看到你是新來的。本網站習慣於接受您認爲有用的答案。否則,人們會更不願意回答您可能會遇到的任何問題。 – Herbert
@abc您應該標記爲接受Herbert的回覆。赫伯特你好,謝謝你正確的聲明,我試圖沒有成功的[w3school](https://www.w3schools.com/js/tryit.asp?filename=tryjs_ajax_post2),與你的相比,他們一看起來混亂和不完整(我想知道它是如何工作的) – Robert