XMLHttpRequest和FormData不提交数据

Man*_*ngo 5 javascript php ajax xmlhttprequest form-data

我正在尝试使用post方法和FormData对象通过ajax提交表单。

这是JavaScript的简化版本:

var form=…; //  form element
var url=…;  //  action
form['update'].onclick=function(event) {    //  button name="update"
    var xhr=new XMLHttpRequest();
        xhr.open('post',url,true);
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    var formData=new FormData(form);
        formData.append('update', true);    // makes no difference
    xhr.send(formData);
    xhr.onload=function() {
        alert(this.response);
    };
};
Run Code Online (Sandbox Code Playgroud)

该表格有:

  • 一个按钮(type="button" name="update")以运行脚本
  • 不,action并且method="get"

我的PHP脚本具有以下内容:

if(isset($_POST['update'])) {
    print_r($_POST);
    exit;
}

//  more stuff

print 'other stuff';
Run Code Online (Sandbox Code Playgroud)

当我尝试它时,PHP进入了其余的代码,并且得到了其他输出,而不是我从print_r语句中期望的输出。

我尝试了以下变体:

  • new FormData()(无表格)。如果我手动添加数据,这确实可行update
  • new FormData(form)。无论我是否update手动添加,这都行不通。
  • 将表单方法更改为post
  • MacOS上的Firefox,Safari和Chrome;所有当前版本。

from本身看起来像这样:

<form id="edit" method="post" action="">
    <p><label for="edit-summary">Summary</label><input id="edit-summary" name="summary" type="text"></p>
    <p><label for="edit-description">Description</label><input id="edit-description" name="description" type="text"></p>
    <p><label for="edit-ref">Reference</label><input id="edit-ref" name="ref" type="text"></p>
    <p><label for="edit-location">Location</label><input id="edit-location" name="location" type="text"></p>
    <p><button type="button" name="update">OK</button></p>
</form>
Run Code Online (Sandbox Code Playgroud)

我应该怎么做才能使这个工作呢?

请不要jQuery。

Mus*_*usa 6

发送FormData对象时,内容类型是multipart / form-data而不是url编码。
此外,必须为请求设置适当的边界,而用户无法执行此边界。为此XMLHttpRequest设置具有所需边界的正确内容类型。
因此,您要做的就是不设置内容类型,它就会起作用。

var xhr=new XMLHttpRequest();
xhr.open('post',url,true);
//xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");<--don't do this
var formData=new FormData(form);
formData.append('update', true);    // makes no difference
xhr.send(formData);
xhr.onload=function() {
    alert(this.response);
};
Run Code Online (Sandbox Code Playgroud)