我用 PHP 编写了 javascript 代码,并想使用 XMLHttpRequest 发送请求。但当 setRequestHeader 设置时,$_POST 总是为 null。如果我删除 setRequestHeader,$_POST 就存在。
这是我的 JavaScript 代码
var xmlhttp = new XMLHttpRequest();
var params = new FormData();
params.append('workername', name);
params.append('address', address);
params.append('email', email);
xmlhttp.open("POST", "searchworker.php", true);
//Send the proper header information along with the request
//xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("workerResult").innerHTML = this.responseText;
}
};
xmlhttp.send(params);
代码结果
print_r($_POST);`
是
Array ( [workername] => green [address] => US [email] => test@example.com )
我可以收到 $_POST 值。但如果取消注释该行
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
我会得到这个结果
Array ( [------WebKitFormBoundaryTBeUMaDsrWBBYRFB Content-Disposition:_form-data;_name] => "workername"
green ------WebKitFormBoundaryTBeUMaDsrWBBYRFB Content-Disposition: form-data; name="address"
US ------WebKitFormBoundaryTBeUMaDsrWBBYRFB Content-Disposition: form-data; name="email"
test@example.com ------WebKitFormBoundaryTBeUMaDsrWBBYRFB--
)
并且所有 $_POST 值为空。
那么我应该使用setRequestHeader吗?因为我在网上读到,如果我们使用 open("POST",...) 我们应该使用 setRequestHeader。是什么原因导致设置setRequestHeader后收不到$_POST?
最佳答案
FormData 对象在发布时会被格式化为 multipart/form-data
正文,而不是 urlencoded 正文。如果您想将数据发布为 application/x-www-form-urlencoded
,您需要自行将帖子正文格式化为 urlencoded 字符串。
var params = 'workername=' + encodeURIComponent(name) + '&address=' + encodeURIComponent(address) + '&email=' + encodeURIComponent(email);
关于javascript - XMLHttpRequest, setRequestHeader 设置时 $_POST 为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48179656/