Web frontier-Use of HTML5 Form Data Objects

Source: Internet
Author: User

XMLHttpRequest Level 2 adds a new interface -- FormDataUse FormDataObject,We can useJavaScriptSome key-value pairs are used to simulate a series of form controls. We can also use the send () method of XMLHttpRequest to asynchronously submit forms. Compared with normal Ajax, the biggest advantage of using FormData is that we can upload binary files asynchronously.

Articles you may be interested in
  • 10 popular Metro UI Bootstrap themes and templates
  • Select 12 excellent jQuery Ajax paging plug-ins and tutorials
  • 10 popular topic Bootstrap in Metro UI Style
  • 8 exquisite jQuery plug-ins for loading animations and progress bars
  • 35 exquisite CSS3 and HTML5 webpage templates are recommended

Create a FormData object

You can create an emptyFormData Object, and then useappend() Method to add fields 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 contains the file oMyForm selected by the user. append ("userfile", fileInputElement. files [0]); var oFileBody = "<a id =" a "> <B id =" B "> hey! </B> </a> "; // The file content contained in the Blob Object 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 of "userfile" and "webmasterfile" contain a file. PassFormData.append() The number assigned to the field "accountnum" is automatically converted to a character (the field value can beBlob Object,FileObject or string. Other types of values are automatically converted to strings ).

In this example, we created a FormData object named oMyForm, which contains the field names named "username", "accountnum", "userfile", and "webmasterfile, then useXMLHttpRequestOfsend() Method to send the data. The value of the "webmasterfile" field is not a string orBlob Object.

Use HTML forms to initialize a FormData object

You can use an existing form Element for initialization.FormData object,Just put thisform Element passed as a parameterFormData 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 add new key-value pairs based on existing form data, as shown below:

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

You can add some fixed fields that you do not want to edit in this way, and then send them again.

Use the FormData object to send files

You can also useFormData To send a binary file. First, the HTML contains a form element that contains the 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="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>

Then you can use the following code to asynchronously upload the selected files:

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);}

You can directlyFormData AddFile Object orBlob Object:

data.append("myfile", myBlob);

If a field value in the FormData object isBlob When an HTTP request is sentBlob The value of the "Content-Disposition" request header of the object's file name varies with different browsers. Firefox uses a fixed string "blob ", chrome uses a random string.

You can also use jQuery to sendFormData, but you must set the relevant options correctly:

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 the Content-Type Request Header });
Browser compatibility

Desktop:

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 7 + 4.0 (2.0) 10 + 12 + 5 +
SupportedfilenameParameters (Yes) 22.0 (22.0) ? ? ?

Mobile Terminal:

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

12 +

?
SupportedfilenameParameters ? ? 22.0 (22.0) ? ? ?

References:

  • MDN: Use XMLHttpRequest
  • MDN: XMLHttpRequest FormData
  • New XMLHttpRequest 2 skills
  • MDN: Use a FormData object
  • W3C: XMLHttpRequest Level 2
Articles you may be interested in
  • 10 latest and popular jQuery plug-ins worth your favorites
  • Exquisite Web application icons
  • Like! 10 sets of exquisite free website background management system templates
  • Amazing foreign creative 404 error page design
  • Classic design: 17 examples of the most effective landing page design

 

Link to this article: front-end Digest: Use of HTML5 Form Data Objects

Source: Dream sky ◆ focus on front-end development technology ◆ share web design resources

Related Article

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.