Big Bear Study HTML5 series------XHR2 (XMLHttpRequest Level 2)

Source: Internet
Author: User
Tags html form

First, the opening analysis

Hi, hello, everyone! Big Bear June again and everyone met, (*^__^*) hehe ..., this series of articles is mainly to learn HTML5 related knowledge points, to learn API knowledge points for the entrance, the introduction of an example,

Let everyone step-by-step experience "h5" can do what, as well as in the actual project how to use the reasonable application to achieve the freedom, the perfect harness O (∩_∩) o~, well, nonsense not much to say, directly into the theme of today,

Today is mainly about the "XMLHttpRequest Level 2 API" and the role in the client browser, and will introduce a practical example to explain the prototype paradigm, let us first look at the "XHR API":

There is such an unsung hero in the HTML5 World: " XMLHttpRequest" . Strictly speaking, XHR2 does not belong to HTML5. However, it is part of the ongoing improvements that browser vendors make to the core platform.

I added "XHR2" to the "H5" series because it plays an integral role in today's complex Web applications, introduces a number of new features (such as cross-origin requests, upload progress events, and support for uploading/downloading binary data).

      

Second, the new knowledge of temperature

  Let's start with a simple review:

 (1), XMLHttpRequest Level 1 object creation

var xhr = new XMLHttpRequest ();

(2), establish a link to the server host and make a request

Xhr.open (' GET ', ' bb.jsp '); Xhr.send ();

(3) Wait for the server host to respond, listen for changes in the state of the XMLHttpRequest object, specify the callback function

Xhr.onreadystatechange = function () {    if (xhr.readystate = = 4 && Xhr.status = =) {    alert (xhr.response Text); }     else{    alert (xhr.statustext);}    ;

  

 To summarize: There are some deficiencies relative to the new version of "XMLHttpRequest Level 2"

 Only text data transfer is supported and cannot be used to read and upload binary files.

When transmitting and receiving data, there is no progress information and can only prompt for completion.

Subject to the same domain restriction (same Origin Policy), data can only be requested from servers of the same domain name.

Some features of the new version are expanded:

 You can set the time limit for HTTP requests.

Xhr.timeout =function(event) {    alert (' request timed out! ');} ;

  (The maximum wait time is set to 3000 milliseconds.) After this time limit, the HTTP request is automatically stopped. There is also a timeout event, which is used to specify the callback function. )

  

You can use the Formdata object to manage form data. (There will be a detailed introduction later.) )

can upload files. (There will be a detailed introduction later.) )

You can request data under different domain names (cross-domain requests).

 HTML 5 Previous standards due to the browser security problem does not allow direct cross-domain communication, so in order to achieve the purpose of cross-domain communication a variety of egg-ache solutions emerged,

Commonly used are: JSONP, the use of proxy files, address bar hash, and so on, the emergence of these methods to solve cross-domain problems, but also increased the front-end page performance and maintenance costs.

The HTML5 new standard adds the " cross-origin Resource sharing" feature, which enables cross-domain communication to be resolved only by configuring the HTTP protocol header.

(Cross-origin Resource sharing the most important thing to achieve is the configuration of the parameter "Access-control-allow-origin", that is, to check whether the cross-domain request can be passed through the secondary parameter.
such as: access-control-allow-origin:http://a.com to allow the domain name under a.com cross-domain access;
access-control-allow-origin:* means that all domain names are allowed cross-domain access. )

  

  If you need to read the read cookie:
Configuration parameters Required: Access-control-allow-credentials:true
Also set the parameter withcredentials to True when XHR initiates the request:
  

    

var xhr = new XMLHttpRequest (); Xhr.open (); xhr.withcredentials = true;  This is done behind Xhr.open, otherwise some versions of the browser will be abnormal, resulting in invalid settings.

The following is a reference example:

  

You can get binary data on the server side.

   The old version of the XMLHttpRequest object, can only retrieve text data from the server, the new version will retrieve the binary data. into two ways. the older approach is to rewrite the mimetype of the data,

Disguises the binary data returned by the server as text data, and tells the browser that this is a user-defined character set.

Xhr.overridemimetype ("Text/plain; Charset=x-user-defined ");

  New version processing mode:

var xhr = new XMLHttpRequest (); Xhr.open (' GET ', '/path/bb.png '); xhr.responsetype = ' blob ';

  

The progress information for the data transfer can be obtained.

  The new version of the XMLHttpRequest object, when transmitting data, has a progress event that is used to return the progress information.

It is divided into two scenarios: Upload and download. The downloaded progress event belongs to the XMLHttpRequest object, and the uploaded progress event belongs to the Xmlhttprequest.upload object.

We first define the callback function for the progress event.

    

xhr.onprogress = updateprogress; xhr.upload.onprogress = updateprogress; function UpdateProgress (event) {    if (  event.lengthcomputable) {var percentcomplete = event.loaded/event.total; }} ;

  In connection with the progress event, there are five other events that can be assigned to a callback function:

  

    * Load Event: Transfer completed successfully.  * Abort event: The transfer was canceled by the user.  * Error Event: A failure occurred in the transmission.  * Loadstart Event: Transfer started. * Loadend Event: Transfer ended, but did not know success or failure.

  

Third, the introduction of the example

  

<! DOCTYPE html>

  

  

The effect is as follows:

  

  

Knowledge Supplement: "FormData" Object

Initializes a Formdata object

var omyform = new FormData (), Omyform.append ("username", "bigbear"), Omyform.append ("AccountNum", 123456); The number 123456 is immediately converted to the string "123456"//Fileinputelement already contains the user selected file Omyform.append ("UserFile", Fileinputelement.files[0] var ofilebody = "<a id=" a "><b id=" B ">hey!</b></a>"; The Blob object contains the file contents var Oblob = new Blob ([Ofilebody], {type: "Text/xml"}), Omyform.append ("Webmasterfile", Oblob);

   Use an HTML form to initialize a Formdata object

var formelement = document.getElementById ("Myformelement"), var oreq = new XMLHttpRequest (); Oreq.open ("POST", " Submitform.php "); Oreq.send (new FormData (formelement)); You can also continue to add new key-value pairs based on existing form data, as follows: var formelement = document.getElementById ("Myformelement"); formData = new FormData (formelement); Formdata.append ("Nick", "BB"); o Req.send (FormData);

 

  

(iv), concluding

(1), understand how the XMLHttpRequest Level 2 API is used and the purpose used in the specific instance is to solve the problem.

(2), XMLHttpRequest Level 2 is different from the previous old version.

(3), skilled use of Formdata objects, and constantly practice and reconstruct the chestnut in the article.

hahaha, the end of this article, not to be continued, hope and we have enough communication, common progress ... To shout ... (*^__^*)      

Big Bear Learn HTML5 series------XHR2 (XMLHttpRequest Level 2)

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.