设置setRequestHeader时,XMLHttpRequest,$ _POST为null

时间:2018-01-10 02:59:14

标签: javascript php ajax

我用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);`

  

阵列(       [workername] =>绿色       [地址] =>我们       [email] => 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;命名="地址"

     

US   ------ WebKitFormBoundaryTBeUMaDsrWBBYRFB Content-Disposition:form-data;命名="电子邮件"

     

test@example.com   ------ WebKitFormBoundaryTBeUMaDsrWBBYRFB -

     

并且所有$ _POST值都为null。

我应该使用setRequestHeader吗?因为我在网上看到,如果我们使用open(" POST",...),我们应该使用setRequestHeader。如果设置setRequestHeader,则无法接收导致$ _POST的内容?

2 个答案:

答案 0 :(得分:1)

FormData对象在发布时会格式化为multipart/form-data正文,而不是urlencoded正文。如果您想将数据发布为application/x-www-form-urlencoded,则需要自己将帖子正文格式化为urlencoded字符串。

var params = 'workername=' + encodeURIComponent(name) + '&address=' + encodeURIComponent(address) + '&email=' + encodeURIComponent(email);

答案 1 :(得分:0)

省略Content-Type标头。浏览器知道如何设置FormData请求。

如果您查看浏览器开发工具网络并检查发送的实际标头,您将看到它设置为:

Content-Type:multipart/form-data; boundary=-----11411516529451

另请注意,您可以将表单元素传递到FormData,并简化必须自己执行所有手动附加

var params = new FormData(document.forms[0]);// or other appropriate dom query
相关问题