XMLHttpRequest Level 2 Adds a new interface--formdata 。
using FormData 对象,
We can simulate a series of form controls using JavaScript with some key-value pairs, and we can also use The XMLHttpRequest Send () method is used to submit the form asynchronously. The biggest advantage of using FormData compared to normal Ajax is that we can upload binary files asynchronously.
You can create an empty object first FormData
, and then use append()
the method to add a field to the object, as follows:
var
oMyForm =
new
FormData();
oMyForm.append(
"username"
,
"Groucho"
);
oMyForm.append(
"accountnum"
, 123456);
// 数字123456被立即转换成字符串"123456"
// fileInputElement中已经包含了用户所选择的文件
oMyForm.append(
"userfile"
, fileInputElement.files[0]);
var
oFileBody =
"<a id="
a
"><b id="
b
">hey!</b></a>"
;
// Blob对象包含的文件内容
var
oBlob =
new
Blob([oFileBody], { type:
"text/xml"
});
oMyForm.append(
"webmasterfile"
, oBlob);
var
oReq =
new
XMLHttpRequest();
oReq.open(
"POST"
,
"http://foo.com/submitform.php"
);
oReq.send(oMyForm);
Note:The values for the fields "UserFile" and "Webmasterfile" contain a file. Pass
FormData.append()
The number that the method assigns to the field "AccountNum" is automatically converted to a character (the value of the field can be a
Blob
Object
File
Object or string, and all other types of values are automatically converted to strings).
In this example, we created a FormData object named Omyform that contains the field names named "username", "AccountNum", "UserFile", and "Webmasterfile", and then uses XMLHttpRequest
the The c1/> method sends the data out. The value of the "Webmasterfile" field is not a string, or an Blob
object.
Use an HTML form to initialize a Formdata object
You can initialize with an existing form element by FormData 对象,
simply form
passing the element as a parameter to the FormData
constructor:
var formelement = document.getElementById ("myformelement");
var oreq = new XMLHttpRequest ();
Oreq.open ("POST", "submitform.php");
Oreq.send (New FormData (formelement));
You can also continue to add a new key-value pair, based on the existing form data, as follows:
var formelement = document.getElementById ("myformelement");
FormData = new FormData (formelement);
Formdata.append ("SerialNumber", serialnumber++);
Oreq.send (FormData);
This way you can add some fixed fields that you don't want the user to edit, and then send them.
You can then use the following code to asynchronously upload a user-selected file:
function Sendform () {
var ooutput = document.getElementById ("Output");
var oData = new FormData (Document.forms.namedItem ("FileInfo"));
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 uploading your file.<br \/>";
}
};
Oreq.send (OData);
}
HTML5 use of the Form Data object