您的请求存在许多问题。如果不使用application/x-www-form-urlencoded,您将无法发布数据。其次,“Hello World!”没有转义或附加到变量。
以下是 POST 数据到服务器的 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的思路。