The use of the Web frontier--html5 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 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.

Related articles that may be of interest to you
    • 10 popular Metro UI Bootstrap themes and templates
    • Featured 12 excellent jQuery Ajax pagination plugins and tutorials
    • 10 popular Metro UI style Bootstrap Themes
    • 8 beautifully crafted JQuery loading animations and progress bar plugins
    • Recommended 35 exquisite CSS3 and HTML5 Web templates

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 =NewFormData (); Omyform.append ("username", "Groucho"); Omyform.append ("AccountNum", 123456);//the number 123456 is immediately converted to the string "123456"//The files selected by the user are already included in the FileinputelementOmyform.append ("UserFile", fileinputelement.files[0]); var ofilebody= "<a id=" a "><b id=" B ">hey!</b></a>";//Blob object contains the file contentsvar Oblob =NewBlob ([Ofilebody], {type: "Text/xml"}); Omyform.append ("Webmasterfile", Oblob); var oreq=NewXMLHttpRequest (); 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 c7/> 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 New FormData (someformelement);

For example:

var formelement = document.getElementById ("myformelement"); var 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"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:

<formenctype= "Multipart/form-data"Method= "POST"name= "FileInfo">  <label>Your Email Address:</label>  <inputtype= "Email"AutoComplete= "On"Autofocus Name= "userid"placeholder= "Email"Required Size= "+"maxlength= " +" /><BR/>  <label>Custom file Label:</label>  <inputtype= "text"name= "Filelabel"size= " a"maxlength= "+" /><BR/>  <label>File to Stash:</label>  <inputtype= "File"name= "File"Required/></form><DivID= "Output"></Div><ahref= "Javascript:sendform ()">Stash the file!</a>

You can then use the following code to asynchronously upload a user-selected file:

functionSendform () {varOoutput = document.getElementById ("Output"); varOData =NewFormData (Document.forms.namedItem ("FileInfo")); Odata.append ("CustomField", "This is some extra data"); varOreq =NewXMLHttpRequest (); 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);}

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 New FormData (document.getElementById ("FileInfo")) fd.append ("CustomField", "This is some extra data"); Ajax ({  "stash.php",  "POST",  data:fd,  false,  //  tell jquery not to handle the data sent  false   //  tell jquery not to set the 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
Related articles that may be of interest to you
    • 10 of the latest popular jQuery plugins, worth your collection
    • Beautiful Web app icon material that's so addictive
    • Praise! 10 sets of beautiful free web site management system templates
    • Those amazing foreign ideas. 404 error page Design
    • Classic design: 17 Most effective examples of learning landing page design

This article link: front-end digest: HTML5 Form Data Object use

Compilation Source: Dream Sky focus on front-end development technology sharing web design resources

The use of the Web frontier--html5 Form Data Object

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.