使用FormData对象

  • 版本网址缩略名: DOM/XMLHttpRequest/FormData/Using_FormData_Objects
  • 版本标题: Using FormData Objects
  • 版本 id: 235725
  • 创建于:
  • 创建者: ziyunfei
  • 是否是当前版本?
  • 评论 64 words added, 227 words removed

修订内容

The FormData object lets you compile a set of key/value pairs to send using XMLHttpRequest. Its primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data. The transmitted data is in the same format that the form's submit() method would use to send the data if the form's encoding type were set to "multipart/form-data".

Creating a FormData object from scratch

You can build a FormData object yourself, instantiating it then appending fields to it by calling its append() method, like this:

var oMyForm = new FormData();

oMyForm.append("username", "Groucho");
oMyForm.append("accountnum", 123456); // 数字123456会被立即自动转换为字符串"123456"

// HTML file input user's choice...
oMyForm.append("userfile", fileInputElement.files[0]);

// JavScript file-like object...
/*
* In the future...:
* var oBlob = new BlobBuilder();
* ...but for now...:
*/
var oBlob = new MozBlobBuilder();

oBlob.append("<a id=\"a\"><b id=\"b\">hey!<\/b><\/a>"); // the body of the new file...

oMyForm.append("webmasterfile", oBlob.getBlob("text\/xml"));

var oReq = new XMLHttpRequest();
oReq.open("POST", "http://foo.com/submitform.php");
oReq.send(oMyForm);
注意: The fields "userfile" and "webmasterfile" contain both a file. The number assigned to the field "accountnum" is immediately converted into a string by the FormData.append() method (the field's value can be a {{ domxref("Blob") }}, {{ domxref("File") }}, or a string: if neither, the value is converted to a string).

This example builds a FormData instance containing values for fields named "username", "accountnum", "userfile" and "webmasterfile", then uses the XMLHttpRequest method send() to send the form's data. The field "webmasterfile" is a Blob. A Blob object represents a file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The {{ domxref("File") }} interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system. In order to build a Blob you can use the getBlob() method of each BlobBuilder instance or invoke the Blob constructor directly.

从一个HTML表单元素生成FormData对象

构造一个FormData对象,该对象包含了一个已经存在的{{ HTMLElement("form") }}元素中的所有数据, 在创建FormData对象时将指定的form元素作为参数传入:

var newFormData = new FormData(someFormElement);

例如:

var formElement = document.getElementById("myFormElement");
var oReq = new XMLHttpRequest();
oReq.open("POST", "submitform.php");
oReq.send(new FormData(formElement));

你也可以在生成FormData对象之后,发送这个对象之前,在这个对象里添加一些附加的数据,像这样:

var formElement = document.getElementById("myFormElement");
formData = new FormData(formElement);
formData.append("serialnumber", serialNumber++);
oReq.send(formData);

append方法可以让你在发送一个表单的数据之前添加额外的数据,这些数据不需要用户在表单中编辑.

使用FormData对象发送文件

你也可以使用 FormData来发送文件. 只需要直接发送一个表单(form)元素,该表单元素必须包含一个type属性为"file"的 {{ HTMLElement("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 />
</form>
<div id="output"></div>
<a href="javascript:sendForm()">Stash the file!</a>

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

function sendForm() {
  var oOutput = document.getElementById("output");
  var oData = new FormData(document.forms.namedItem("fileinfo"));

  oData.append("自定义字段", "这是一些额外数据");

  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 + " 上传文件时发生错误.<br \/>";
    }
  };

  oReq.send(oData);
}

上例将一个文件传给了服务器上的一个php脚本,并且处理了可能发生的HTTP错误.

你也可以将一个 {{ domxref("File") }}对象或者{{ domxref("Blob") }}对象直接添加进这个{{ domxref("XMLHttpRequest/FormData", "FormData") }} 对象中,像这样:

data.append("myfile", myBlob);

如果使用了 {{ domxref("Blob") }},则在发送到服务器上的代表该文件的文件名的"Content-Disposition"字段的值在各浏览器中是有差别的,Firefox简单的使用一个字符串"blob",而Chrome使用一个随机字符串,等等.

你也可以在jQuery中使用FormData,但必须正确的设置相关选项:

var fd = new FormData(document.getElementById("fileinfo"));
fd.append("自定义字段", "这是一些额外数据");
$.ajax({
  url: "stash.php",
  type: "POST",
  data: fd,
  processData: false,  // 告诉jQuery不要处理发送的数据
  contentType: false   // 告诉jQuery不要去设置contentType属性的值
});

 

{{ languages( {"en": "en/DOM/XMLHttpRequest/FormData/Using_FormData_Objects" } ) }}

修订版来源

<p>The <a href="/zh-cn/DOM/XMLHttpRequest/FormData" title="zh-cn/DOM/XMLHttpRequest/FormData"><code>FormData</code></a> object lets you compile a set of key/value pairs to send using <code>XMLHttpRequest</code>. Its primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data. The transmitted data is in the same format that the form's <code>submit()</code> method would use to send the data if the form's encoding type were set to "multipart/form-data".</p>
<h2>Creating a FormData object from scratch</h2>
<p>You can build a <code>FormData</code> object yourself, instantiating it then appending fields to it by calling its <a href="/zh-cn/DOM/XMLHttpRequest/FormData#append()" title="zh-cn/XMLHttpRequest/FormData#append()"><code>append()</code></a> method, like this:</p>
<pre class="deki-transform">var oMyForm = new FormData();

oMyForm.append("username", "Groucho");
oMyForm.append("accountnum", 123456); // 数字123456会被立即自动转换为字符串"123456"

// HTML file input user's choice...
oMyForm.append("userfile", fileInputElement.files[0]);

// JavScript file-like object...
/*
* In the future...:
* var oBlob = new BlobBuilder();
* ...but for now...:
*/
var oBlob = new MozBlobBuilder();

oBlob.append("&lt;a id=\"a\"&gt;&lt;b id=\"b\"&gt;hey!&lt;\/b&gt;&lt;\/a&gt;"); // the body of the new file...

oMyForm.append("webmasterfile", oBlob.getBlob("text\/xml"));

var oReq = new XMLHttpRequest();
oReq.open("POST", "http://foo.com/submitform.php");
oReq.send(oMyForm);
</pre>
<div class="note"><strong>注意:</strong> The fields "userfile" and "webmasterfile" contain both a file. The number assigned to the field "accountnum" is immediately converted into a string by the <a href="/zh-cn/DOM/XMLHttpRequest/FormData#append()" title="zh-cn/XMLHttpRequest/FormData#append()"><code>FormData.append()</code></a> method (the field's value can be a {{ domxref("Blob") }}, {{ domxref("File") }}, or a string: <strong>if neither, the value is converted to a string</strong>).</div>
<p>This example builds a <code>FormData</code> instance containing values for fields named "username", "accountnum", "userfile" and "webmasterfile", then uses the <code>XMLHttpRequest</code> method <a href="/zh-cn/DOM/XMLHttpRequest#send()" title="zh-cn/XMLHttpRequest#send()"><code>send()</code></a> to send the form's data. The field "webmasterfile" is a <a href="/zh-cn/DOM/Blob" title="zh-cn/DOM/Blob"><code>Blob</code></a>. A <a href="/zh-cn/DOM/Blob" title="zh-cn/DOM/Blob"><code>Blob</code></a> object represents a file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The {{ domxref("File") }} interface is based on <a href="/zh-cn/DOM/Blob" title="zh-cn/DOM/Blob"><code>Blob</code></a>, inheriting blob functionality and expanding it to support files on the user's system. In order to build a <a href="/zh-cn/DOM/Blob" title="zh-cn/DOM/Blob"><code>Blob</code></a> you can use the <a href="/zh-cn/DOM/BlobBuilder#getBlob()" title="zh-cn/DOM/BlobBuilder#getBlob()"><code>getBlob()</code></a> method of each <a href="/zh-cn/DOM/BlobBuilder" title="zh-cn/DOM/BlobBuilder"><code>BlobBuilder</code></a> instance or <strong>invoke the <a href="/zh-cn/DOM/Blob#Constructor" title="zh-cn/DOM/Blob#Constructor"><code>Blob</code> constructor</a> directly</strong>.</p>
<h2>从一个HTML表单元素生成FormData对象</h2>
<p>构造一个<code>FormData对象</code>,该对象包含了一个已经存在的{{ HTMLElement("form") }}元素中的所有数据, 在创建<code>FormData对象时将指定的form元素作为参数传入</code>:</p>
<pre>var newFormData = new FormData(someFormElement);
</pre>
<p>例如:</p>
<pre class="deki-transform">var formElement = document.getElementById("myFormElement");
var oReq = new XMLHttpRequest();
oReq.open("POST", "submitform.php");
oReq.send(new FormData(formElement));
</pre>
<p>你也可以在生成<code>FormData</code>对象之后,发送这个对象之前,在这个对象里添加一些附加的数据,像这样:</p>
<pre class="deki-transform">var formElement = document.getElementById("myFormElement");
formData = new FormData(formElement);
formData.append("serialnumber", serialNumber++);
oReq.send(formData);
</pre>
<p><code>append</code>方法可以让你在发送一个表单的数据之前添加额外的数据,这些数据不需要用户在表单中编辑.</p>
<h2>使用FormData对象发送文件</h2>
<p>你也可以使用 <code>FormData来发送文件</code>. 只需要直接发送一个表单(form)元素,该表单元素必须包含一个type属性为"file"的 {{ HTMLElement("input") }} 元素:</p>
<pre class="deki-transform">&lt;form enctype="multipart/form-data" method="post" name="fileinfo"&gt;
  &lt;label&gt;Your email address:&lt;/label&gt;
  &lt;input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" /&gt;&lt;br /&gt;
  &lt;label&gt;Custom file label:&lt;/label&gt;
  &lt;input type="text" name="filelabel" size="12" maxlength="32" /&gt;&lt;br /&gt;
  &lt;label&gt;File to stash:&lt;/label&gt;
  &lt;input type="file" name="file" required /&gt;
&lt;/form&gt;
&lt;div id="output"&gt;&lt;/div&gt;
&lt;a href="javascript:sendForm()"&gt;Stash the file!&lt;/a&gt;
</pre>
<p>然后你可以使用下面的代码发送它:</p>
<pre class="deki-transform">function sendForm() {
  var oOutput = document.getElementById("output");
  var oData = new FormData(document.forms.namedItem("fileinfo"));

  oData.append("自定义字段", "这是一些额外数据");

  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 + " 上传文件时发生错误.&lt;br \/&gt;";
    }
  };

  oReq.send(oData);
}
</pre>
<p>上例将一个文件传给了服务器上的一个php脚本,并且处理了可能发生的HTTP错误.</p>
<p>你也可以将一个 {{ domxref("File") }}对象或者{{ domxref("Blob") }}对象直接添加进这个{{ domxref("XMLHttpRequest/FormData", "FormData") }} 对象中,像这样:</p>
<pre>data.append("myfile", myBlob);
</pre>
<p>如果使用了 {{ domxref("Blob") }},则在发送到服务器上的代表该文件的文件名的"Content-Disposition"字段的值在各浏览器中是有差别的,Firefox简单的使用一个字符串"blob",而Chrome使用一个随机字符串,等等.</p>
<p>你也可以在jQuery中使用<code>FormData,但必须正确的设置相关选项</code>:</p>
<pre class="deki-transform">var fd = new FormData(document.getElementById("fileinfo"));
fd.append("自定义字段", "这是一些额外数据");
$.ajax({
  url: "stash.php",
  type: "POST",
  data: fd,
  processData: false,  // 告诉jQuery不要处理发送的数据
  contentType: false   // 告诉jQuery不要去设置contentType属性的值
});
</pre>
<p> </p>
<p>{{ languages( {"en": "en/DOM/XMLHttpRequest/FormData/Using_FormData_Objects" } ) }}</p>
恢复到这个版本