HTML5 use of the Form Data object

Source: Internet
Author: User

  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 XMLHttpRequest's send () method to submit the form asynchronously. The biggest advantage of using FormData compared to normal Ajax is that we can upload binary files asynchronously.

Create a Formdata object

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); The number 123456 is immediately converted to the string "123456"//Fileinputelement already contains the user selected file Omyform.append ("UserFile", Fileinputelement.files[0] ); var ofilebody = "<a id=" a "><b id=" B ">hey!</b></a>"; The Blob object contains the file contents 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 field "UserFile" and "Webmasterfile" contain a file. The FormData.append()  number assigned to the field "AccountNum" by the method is automatically converted to a character (the value of the field can be an Blob  object, an File object, or a 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 newformdata = new FormData (someformelement);

  

For example:

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.

Sending files using the Formdata object

You can also use FormData  to send binary files. First, in HTML, you have a form element that contains a file input box.

<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= "/><br/>  <label>custom file label:</label> <input  type=" text "Name=" Filelabel "size=" "maxlength="/><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>

  

  

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 = =) {      ooutput.innerhtml = "uploaded!";    } else {      oout put.innerhtml = "Error" + oreq.status + "occurred uploading your file.<br \/>";    }  ;   Oreq.send (oData);}

  

  

You can also FormData  add an object File  or an object directly to an object without the help of an HTML form Blob  :

Data.append ("MyFile", Myblob);

  

If a field value in an FormData object is an Blob  object, the value of the Blob  "Content-disposition" request header representing the file name of the object contained in the HTTP request will differ under different browsers when it is sent. Firefox uses a fixed string "blob", and Chrome uses a random string.

You can also use JQuery to sendFormData,但必须要正确的设置相关选项:

var fd = new FormData (document.getElementById ("FileInfo")), Fd.append ("CustomField", "This is some extra data"), $.ajax ({  URL: "stash.php",  Type: "POST",  data:fd,  processdata:false,  //Tell jquery not to process the sent data  Contenttype:false   //Tell jquery not to set Content-type request header});

  

  

Browser compatibility

Desktop side:

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic Support 7+ 4.0 (2.0) + 12+ 5+
Support filename Parameters (Yes) 22.0 (22.0) ? ? ?

Mobile side:

Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support 3.0 4.0 (2.0)

12+

support filename parameter 22.0 (22.0)

Reference documents:

    • MDN: Using XMLHttpRequest
    • Mdn:xmlhttprequest FormData
    • XMLHttpRequest 2 New Tricks
    • MDN: Using the FormData object
    • W3c:xmlhttprequest Level 2

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.