【问题标题】:XMLHttpRequest, $_POST is null when setRequestHeader is setXMLHttpRequest,设置 setRequestHeader 时 $_POST 为空
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 谢谢。这项工作...以前我尝试过不使用 encodeURIComponent(),但它不起作用。
【解决方案2】:

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

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

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

还请注意,您可以将表单元素传递给 FormData 并简化必须自己完成所有手动附加操作

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

【讨论】:

  • 所以如果我们使用FormData(),那么就不需要加上setRequestHeader()...
猜你喜欢
  • 2013-10-13
  • 1970-01-01
  • 2013-06-16
  • 2015-09-19
  • 2013-02-18
  • 2016-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多