No refresh file upload is a common and somewhat complex problem, the common solution is to construct an IFRAME implementation.
In HTML5, a FormData object API is provided, which makes it easy to construct a form request and send it through XMLHttpRequest via FormData. It is also possible to send files through the FormData object, so there is no flash upload to become very simple.
So how does FormData use it? The following is a simple introduction to this cloud-dwelling community.
1. Construct FormData objects
Want a Formdata object, very simple:
var fd = new FormData ();
The FormData object provides only one method append, which is used to add form request parameters to the object.
In the current mainstream browser, you can get or modify formdata in the following two ways.
Method One: Create an empty Formdata object, and then add the key-value pairs individually by using the Append method. Example:
var fd = new FormData ();
Fd.append ("name", "cloud-dwelling community");
Fd.append ("blog", "Http://jb51.net");
Fd.append ("File", document.getElementById ("file"));
This method can exist for form objects that do not require HTML.
Method Two: Get the form element object and pass it into the Formdata object as a parameter. Example:
var formobj = document.getElementById ("form");
var fd = new FormData (formobj);
Of course, you can also use the Append method to continue adding additional parameters to the FD.
2. FormData Send Request
Get the FormData object, how to send the request? The FormData object is primarily used in the Send method of an enhanced XMLHttpRequest object. Refer to the following example:
var xhr = new XMLHttpRequest ();
Xhr.open ("POST", "Http://jb51.net", true);
Xhr.send (FD);
Xhr.onload = function (e) {
if (this.status = =) {
alert (this.responsetext);
}
;
3. Using FormData in jquery
In the JQuery Ajax method, you can also use the FormData method to achieve no refresh upload. However, to note the parameters of the settings, refer to the following:
$.ajax ({
URL: "http://jb51.net",
type: ' POST ',
data:fd,
/**
* must be false to automatically add correct Content-type * *
contenttype:false,
/**
* must be false to avoid jquery's default handling of Formdata
* XMLHttpRequest to Formdata Do the proper processing
/Processdata:false
}). Done (function (result) {
console.log (result);
}). Fail (function (err) {
console.log (err);
});
4. A complete example (including examples of PHP processing):
<?php//php receives form submission information and prints if (isset ($_request[' do ')) {var_dump ($_request);
Var_dump ($_files);
Die (); }?> <! DOCTYPE html>