PHP and HTML5 FormData are used to upload a non-refreshing file,
Upload without refreshing files is a common and complex problem. The common solution is to construct iframe.
In HTML5, A FormData object API is provided. Using FormData, you can easily construct a form request and send it through XMLHttpRequest. It is also possible to send files through the FormData object, so that it becomes very simple without refreshing new uploads.
So how to use FormData? The following is a brief introduction of this.
1. Construct a FormData object
Getting a FormData object is simple:
var fd = new FormData();
The FormData object only provides one method append, which is used to add form request parameters to the object.
In the current mainstream browsers, you can obtain or modify FormData in the following two ways.
Method 1: Create an empty FormData object, and then use the append method to add key-value pairs one by one. Example:
Var fd = new FormData (); fd. append ("name", ""); fd. append ("blog", "http://jb51.net"); fd. append ("file", document. getElementById ("file "));
This method does not require the existence of HTML form objects.
Method 2: Obtain the form Element Object and pass it as a parameter to the FormData object. Example:
var formobj = document.getElementById("form");var fd = new FormData(formobj);
You can also use the append method to add other parameters to fd.
2. Send a request using FormData
How can I send a request to get the FormData object? FormData objects are mainly used in the send method of the enhanced XMLHttpRequest object. See the following example:
var xhr = new XMLHttpRequest(); xhr.open("POST" ,"http://jb51.net" , true);xhr.send(fd);xhr.onload = function(e) { if (this.status == 200) { alert(this.responseText); }};
3. Use FormData in jquery
In the ajax method of jQuery, you can also use the FormData method to achieve no refreshing upload. However, pay attention to the parameter settings as follows:
$. Ajax ({url: "http://jb51.net", type: 'post', data: fd,/*** must be false to automatically add the correct Content-Type */contentType: false, /*** it must be false to avoid jQuery's default formdata Processing * XMLHttpRequest will correctly process formdata */processData: false }). done (function (result) {console. log (result );}). fail (function (err) {console. log (err );});
4. A complete example (including the PHP processing example ):
<? Php // php receives the form submission information and prints if (isset ($ _ REQUEST ['do ']) {var_dump ($ _ REQUEST); var_dump ($ _ FILES ); die () ;}?> <! Doctype html>