【发布时间】:2018-06-19 03:57:33
【问题描述】:
我用 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);`
是
数组 ( [工人姓名] => 绿色 [地址] => 美国 [电子邮件] => test@example.com)
我可以收到 $_POST 值。但是如果取消注释该行
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
我会得到这个结果
数组 ( [-----WebKitFormBoundaryTBeUMaDsrWBBYRFB Content-Disposition:_form-data;_name] => "workername"
绿色 ------WebKitFormBoundaryTBeUMaDsrWBBYRFB Content-Disposition: form-data;名称="地址"
美国 ------WebKitFormBoundaryTBeUMaDsrWBBYRFB Content-Disposition: form-data;名称="电子邮件"
test@example.com ------WebKitFormBoundaryTBeUMaDsrWBBYRFB--
)
并且所有 $_POST 值都是空的。
那么我应该使用 setRequestHeader 吗?因为我在网上看到,如果我们使用 open("POST",...) 我们应该使用 setRequestHeader。设置了 setRequestHeader 是什么原因导致 $_POST 收不到?
【问题讨论】:
-
我认为当
XMLHttpRequestInstance.send()将FormDataInstance作为其参数时,它已经被URL 编码了。
标签: javascript php ajax