JavaScript—异步提交表单的6种方式

FormData的详细介绍及使用请点击此处,那里对FormData的方法和事件已经表述的非常清楚,这里就不再浪费时间在介绍一遍了。本文主要针对FormData对象的使用以及异步文件上传进行详细的说明。

FormData对象可以让我们组织一个使用XMLHttpRequest对象发送的键值对的集合。它主要用于发送表单数据,但是可以独立于使用表单传输的数据。

1、从头开始创建一个FormData对象

你可以创建一个你自己的FormData对象,然后通过append() 方法向对象中添加键值对,就像下面这样:

var formData = new FormData();

formData.append("username", "Groucho");
formData.append("accountnum", 123456); // number 123456 is immediately converted to a string "123456"

// HTML file input, chosen by user
formData.append("userfile", fileInputElement.files[0]);

// JavaScript file-like object
var content = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file...
var blob = new Blob([content], { type: "text/xml"});

formData.append("webmasterfile", blob);

var request = new XMLHttpRequest();
request.open("POST", "http://foo.com/submitform.php");
request.send(formData);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

注意:字段”userfile” 和 “webmasterfile” 都包含文件(file)。被分配到字段”accountnum”上的数字直接被FormData.append()方法转换成了字符串(字段的值(value)可能是一个Blob, File, 或一个string:如果值既不是Blob也不是File,则值会被转换成一个string)。

这个例子创建了一个FormData实例,其中包含字段”username”, “accountnum”, “userfile” 和 “webmasterfile”,然后使用XMLHttpRequest对象的send()方法去发送表单数据。字段”webmasterfile”是一个Blob。一个Blob对象代表一个文件对象的原始数据。但是Blob代表的数据不必须是javascript原生格式的数据。文件接口是基于Blob,继承Blob功能和扩大它对用户文件系统的支持。为了构建一个Blob可以调用Blob()构造函数。

2、从一个HTML表单获得一个FormData对象

为了获得一个包含已存在表单数据的FormData对象,在创建FormData对象的时候需要指定表单元素。

var formData = new FormData(someFormElement);
  • 1

就像下面这样:

var formElement = document.querySelector("form");
var request = new XMLHttpRequest();
request.open("POST", "submitform.php");
request.send(new FormData(formElement));
  • 1
  • 2
  • 3
  • 4

你也可以在获得FormData对象之后增加另外的数据,就像下面这样:

var formElement = document.querySelector("form");
var formData = new FormData(formElement);
var request = new XMLHttpRequest();
request.open("POST", "submitform.php");
formData.append("serialnumber", serialNumber++);
request.send(formData);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

这样你可以在发送之前增加额外的信息,不一定是用户编辑的。

3、使用FormData对象发送文件

你可以使用FormData发送文件。简单的<form>中在包含一个<input>元素就可以:

<form enctype="multipart/form-data" method="post" name="fileinfo">
  <label>Your email address:</label>
  <input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" /><br />
  <label>Custom file label:</label>
  <input type="text" name="filelabel" size="12" maxlength="32" /><br />
  <label>File to stash:</label>
  <input type="file" name="file" required />
  <input type="submit" value="Stash the file!" />
</form>
<div></div>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

然后你可以使用下面的代码去发送:

var form = document.forms.namedItem("fileinfo");
form.addEventListener('submit', function(ev) {

  var oOutput = document.querySelector("div"),
      oData = new FormData(form);

  oData.append("CustomField", "This is some extra data");

  var oReq = new XMLHttpRequest();
  oReq.open("POST", "stash.php", true);
  oReq.onload = function(oEvent) {
    if (oReq.status == 200) {
      oOutput.innerHTML = "Uploaded!";
    } else {
      oOutput.innerHTML = "Error " + oReq.status + " occurred when trying to upload your file.<br />";
    }
  };

  oReq.send(oData);
  ev.preventDefault();
}, false);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

你也可以直接向FormData对象中添加File或Blob,就像下面这样:

data.append("myfile", myBlob, "filename.txt");
  • 1

当使用append() 方法的时候,可能会使用到第三个参数去发送文件名称(通过Content-Disposition头发送到服务器)。如果没有指定第三个参数或这个参数不被支持的话,第三个参数默认是”blob”。

如果你设置好正确的options,你也可以和jQuery配合起来使用:

var fd = new FormData(document.querySelector("form"));
fd.append("CustomField", "This is some extra data");
$.ajax({
  url: "stash.php",
  type: "POST",
  data: fd,
  processData: false,  // tell jQuery not to process the data
  contentType: false   // tell jQuery not to set contentType
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
原文地址:https://www.cnblogs.com/cxsabc/p/10627632.html