XMLHTTPREQUEST is a browser interface. With it, we can make JavaScript communicate with HTTP (s). XMLHTTPREQUEST is a commonly used way to interact data in the present browser. In February 2008, XMLHTTPREQUEST Level 2 was proposed. Compared to the previous generation, it has some new features. Among them, FormData is a new object of XMLHTTPRequest Level 2. It uses it to submit forms and simulating forms. Of course The advantage is that you can upload binary files. Let's introduce how to upload files with FormData.
FormData upload file instanceFirst look at the basic way of FormData: FormData object, you can form a QueryString of all the table elements and value and submit it to the background. Just pass the form form as a parameter into the FormData constructor:
var Form = DOCUMENT.GetelementByid (form1); var fd = new formData (form);
In this way, the FD can be sent directly through the ajax send () method to the background.
The following form Form is created. In addition to ordinary data in the form, there are files uploading. We directly pass Form objects as parameters into FormData objects:
<FORM NAME = FORM1 ID = FORM1> <p> name: <input type = text name = name /> <p> Gender: <input type = radio name = gender value = 1 /> male <input type = Radio name = Gender Value = 2 /P> Female < /p> <p> STU-Number: <input Type = Text Name = Number /> < /p> <p> Photo: <input Type = File Name = Photo ID = PHOTO> </P> <p> <input Type = Button name = b1 value = submit onclick = fsubmit ()/P> </Form> <div ID = result> </div>
The above code creates a form, simply fill in some information, and select a picture as the avatar, set a div to store the result of the return.
For simple, we still use ajax encapsulated by jquery to transfer data to the background:
Function fsubmit () {var Form = Document.GetelementByid (form1); var FD = New FormData (Form); $ .ajax ({url: server.php, type: post, data: fd, processdat a: false, // tell JQuery Don't process the sending data ContentType: False, // Tell jQuery not to set the Content-Type request head SUCCESS: Function (Response, Status, XHR) {console.log (xhr); VAR JSON = $. Pars ejson (Response) ; VAR Result = ''; Result+= Personal information: <br/> name:+json ['name']+<br/> Gender:+json ['gender']+<br/> number:+json [ 'NUMBER']; Result + = '<br/> Avatar: <IMG SRC =' + JSON ['Photo'] + 'Height = 100 style = border-radius: 50%; />'; ') .html (result);}}); Return false;}
The server.php in the above code is the file of the server, receiving the AJAX request, and returning the receiving result. The specific code is as follows:
<? PHP $ name = isset ($ _ Post ['name'])? $ _post ['name']: ''; $ gender = isset ($ _ post ['Genender'])? ''; $ Number = Isset ($ _ Post ['Number'])? Strrpos ($ _ files ['Photo'] ['name'], '.'); Lename)) {{ $ Response ['ISSUCCCESS'] = TRUE; $ Response ['name'] = $ Name; $ response ['gender'] = $ gender; $ response ['number'] = $ number; $ Response ['Photo'] = $ FILENAME;} Else {$ Response ['issuccess'] = false;} echo json_encode ($ response);?>
After filling in the information, click Submit to get the following effects on the page. You can also find the picture uploaded under the corresponding folder of the server.
If you are a native JavaScript enthusiast, of course, the above functions can be achieved. Below is a simple JavaScript implementation code:
Function fsubmit () {var Form = Document.GetelementByid (form1); var formData = New FormData (Form); alert (formData.Name); var olo re = new xmlhtprequest (). ; oreq.OnReadyStateChange = Function () {if (olq . READYSTATE == 4) {if (oreq.status == 200) {console.log (typeof oreq.Responsetext); var json = json.parse (oreq.Responsetext); VAR Result = ''; Result + = Personal information : <br/> name:+json ['name']+<br/> Gender:+json ['gender']+<br/> number:+json ['number']; result+= '<<<<<br/ > Avatar: <IMG SRC = ' + JSON [' Photo '] +' Height = 50 STYLE = Border-Radius: 50%; /> '; $ ('#Result '). oreq.open (post, server.php); oreq.send (formdata); return false;}FormData object method introduction
In addition to the new objects above FormData, Form is directly passed into the parameter, and there are other functions. Most of the articles introduced by FormData on the Internet only mention the APEND () method. So what are the methods of FormData objects? Let's console to know:
After Console, we have a major discovery. The FormData object has such a method, so you can test the truth by yourself. Here are one of these methods:
1. APEND ()Append () method is used to add key values to the FormData object:
fd.append ('Key1', Value1); fd.append ('key2', value2);
FD is the object of FormData, which can be newly built. It can also include the Form form or other key values pairs.
2. SET ())Set the corresponding key key value value (s)
fd.set ('key1', value1); fd.set ('key2', value2);
It looks a bit similar to the Append () method. The difference between the two is that when the specified key value exists, the Append () method is Cover the key value pair of the previous settings. Still compare through the example, we are based on the ahead of Form's Form.
fd.append ('name', Will);
Two key is the key value of name:
fd.set ('name', Will);
Only one key is the key value of name:
The above is the difference between Append () and set (). If the set value set does not exist, the effect of the two is the same.
3. Delete ()Receive a parameter, indicating that the name of the key value you want to delete, if there are multiple same key values, it will delete it:
fd.append ('name', 'will'); fd.delete ('name');
The name information in Form and the newly added name information through APPEND () have been deleted.
4. get () and getall ()Receive a parameter to indicate the name of the key you need to find, and return the first value value of the first key. If there are multiple same key, and return all the corresponding value value of this key.
Based on the above form form:
fd.append ('name', 'will'); console.log (fd.get ('name')); // Sean
fd.append ('name', 'will'); console.log (fd.getall ('name')); // [sean, Will]5. Has ()
This method also receives a parameter, which is also the name of the key, returning a Boolean value to determine whether the FormData object contains the key. The above form is an example:
console.log (fd.has ('name')); // TrueConsole.log (fd.has ('name')); // false6. Keys ()
This method does not need to receive parameters, and return a iterator. Through this iterator, we can traverse all the key in the FormData object. The above form is an example:
for (var key of fd.keys ()) {console.log (key);}
The result is:
name
gender
number
Photo
7. Values ()With the iterative of the key, of course, it is indispensable to traversed the Value iterator. Values () is an iterator of the Value. The usage is similar to keys ():
for (var value of fd.values ()) {console.log (value);}
result:
8. Entries ()There is a iterator that traverses the KEY, and there are also the iterators of Value, why not engage in a two together! ENTRIES () is to return an iterator containing a key value pair:
for (var pair of fd.entries ()) {console.log (pair [0]+ ','+ pair [1]);}
result:
FormData compatibility problemSince FormData is a new interface of XMLHTTPREQUEST Level 2, the IE browser that is now lower than IE10 does not support FormData. As for the method of FormData object introduced above, it is not supported in the IE browser. The support situation can refer to the figure below:
The above is all the contents of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support VEVB Wulin.com.