The beauty of JavaScript Ajax ~

Source: Internet
Author: User
Tags html form xml dom document chrome developer

There was a period of time, because the developer of the misuse of JavaScript led to a period of unpopular times, not be optimistic, and then, to 2005 years, Google's many technologies are used Ajax, JavaScript is again hot up, can say, Ajax has saved JavaScript, and for now, being proficient in using Ajax has become a skill that all Web developers have to master. So what about Ajax? What is the role of it?

The first part: Introduction to Ajax

Ajax is shorthand for asynchronous JavaScript +xml, a technique that can request additional data from the server without uninstalling the page, resulting in a better user experience. The core of Ajax is the XMLHttpRequest object (abbreviated XHR, which is supported by mainstream browsers such as Chrome, Safari, FF, opera, etc.), a feature introduced by Microsoft, IE (5 and 6) using ActiveXObject , the same implementation was later provided by the browser provider. the existence of the XHR object means that when the user clicks it, it is possible to get new data from the background without having to refresh the page, that is, you can try the Xhr object to get new data, and then insert the new data into the page in the DOM way to update the part of the page. It is worth noting that although Ajax contains XML, we do not need to refresh the page to get the data is not necessarily XML data, such as can be text data or JSON data.

Part II: Creation of XHR objects

As mentioned above, the core of Ajax is the XMLHttpRequest object, so how do we create a XMLHttpRequest object?

First, we should know that all browsers support XMLHttpRequest objects, where IE5 and IE6 use ActiveXObject objects. And now all browsers (ie7+, FireFox, Chrome, Safari, and Opera) have built-in XMLHttpRequest objects. So the syntax for creating XMLHttpRequest objects is:

1 varxhr = newXMLHttpRequest();

Just mentioned that older versions of Internet Explorer (IE5 and IE6) use ActiveXObject objects, so the syntax is:

1 varaxo = newActiveXObject("Microsoft.XMLHTTP");

Note: The incoming "microsoft.xmlhttp" cannot be changed.

Therefore, in order to deal with all modern browsers ( including IE5 and IE6), first check whether the XMLHttpRequest object is supported: if supported, the XMLHttpRequest object is created; The ActiveXObject object is created:

123456789 varxmlHttp=null;if(window.XMLHttpRequest){      xmlHttp=new XMLHttpRequest();}else{    xlmHttp=newActiveXObject("Microsoft.XMLHTTP");}

The code for this response to all modern browsers should be noted:

    • I set the value of XMLHTTP to null because a null value represents an empty object pointer, which is why using the TypeOf operator to detect that a null value is returning "Object", so: if the defined variable is ready to be used in the future to save the object , it is better to initialize the variable to null instead of the other value.
    • You can try window. XMLHttpRequest to detect if it exists because XMLHttpRequest is a property of the Window object.

Part III: Usage of XHR objects (properties and methods, etc.)

In the above two sections, we describe what the XHR object is and how to create it, and this Part I will talk about the usage of the XHR object.

  ⑴.open () method

Since XHR is an object, it must have its own properties and methods. When using a Xhr object, the first method to invoke is open (). It accepts 3 parameters:

    1. The type of request to send: Get, post, put, delete, and so on.
    2. The requested URL (this URL can be either an absolute or a relative path).
    3. The Boolean value of whether to send the request asynchronously : True indicates that the request was sent asynchronously, and false indicates that the request was sent synchronously.

( supplemental: We do not recommend the use of Async=false because JavaScript waits until the server responds ready to continue, and if the server is busy or slow, the application hangs or stops )

Examples are as follows:

1 xhr.open("get","example.php",true);

At this point, the code initiates a GET request for example.php . Note: The Open () method does not actually send the request but only initiates a request for sending . So how to send a specific request, this is the use of the Send () method.

  

⑵.Send () method

  Just talking about the open () method, just open, not yet sent, and send is really sent. It takes a parameter:

    • Data sent as the request Principal

  Note: If you do not need to send data through the request principal, you must pass in NULL. A generic GET request does not require an incoming parameter , and for a POST request, if you need to post data like an HTML form, use setRequestHeader () to add an HTTP header . Then specify the data you want to send in the Send () method. This section will be described in detail, here is a simple example:

12 xhr.open("get","example.php",true);xhr.send(null);

  

(3). Several properties of the Xhr object

When sent through send (), the response is accepted and the response data is automatically populated with the properties of the Xhr object. There are mainly the following types:

    • ResponseText: Text returned as the response body
    • Responsexml: If the content type of the response is "text/xml" or "application/xml", this property will hold the XML DOM document containing the corresponding data.
    • Status: HTTP status of the response
    • Description of the Statustext:http status

When a response is received, the Status property is typically checked to determine if the response returned successfully, and a general status code of 200 indicates success (which starts with 2), which is responsetext to be accessed. A status code of 304 indicates that the requested resource has not been modified and can be used directly from the cached version in the browser, so this response is also valid. You can then detect the two states by using the following code:

1234567 xhr.open("get","example.php",false);xhr.send(null);if((xhr.status>=200&&xhr.status<300)||xhr.status==304){    alert(xhr.responseText);}else{    alert("Request waw unseccessful:"+"xhr.status");}

  

The ReadyState property of the Xhr object

Using Ajax we would of course want to send an asynchronous request: If a sync request is sent, then once the NIC is in, the page will not react but continue to wait for the response, but send an asynchronous request, even if the NIC is live, without worrying because it is asynchronous. the ReadyState property can detect the current active phase of the request/response process . It has 5 values, respectively, as follows:

key: as long as the value of the readystate changes (such as from 0 to 1, from 1 to 2, etc.), then each change will trigger the ReadyStateChange event. And it is possible to detect the value of the readystate after each state change by this time. The value of 4 is the most important because all the data is ready. See an example:

123456789101112 varxhr=newXMLHttpRequest();xhr.open("get","example.php",false);xhr.onreadystatechange=function(){    if(readyState==4){        if((xhr.status>=200&&xhr.status<300)||xhr.status==304){            alert(xhr.responseText);        }else{            alert("Request waw unseccessful:"+"xhr.status");        }    }};xhr.send(null);

Note the following points:

    • Xhr.onreadystatechange is preceded by an on, because we are using the DOM0-level method to add a time handler for the Xhr object, without using the DOM2-level method of AddEventListener, is because not all browsers support the DOM2-level approach .
    • In this example, we are not using this object because of the scope problem of the onreadystatechange time handler. If you use the This object, in some browsers it can cause the function to fail or cause an error to occur. Therefore, it is a more reliable way to use actual instances of XHR objects to facilitate that.

(4). Abort () method

Before accepting the response, we can also use the Abort () method to cancel the asynchronous request as follows:

1 xhr.abort();

After this method is called, the XHR object stops triggering the event and no longer allows access to any object properties related to the response.

(5) The setRequestHeader () method, the getResponseHeader () method, the Getallresponseheader () method are explained after the introduction of part fourth

Part IV: HTTP header information

Because the use of Ajax and background interaction, then must be inseparable from the HTTP protocol. The HTTP request and response will have the appropriate header information.

  By default, the following header information is also sent at the same time that the XHR request is sent.

    • Accept: Content types that the browser can handle
    • Accept-charset: The character set that the browser can display
    • Accept-encodding: Compression encoding that the browser can handle
    • Accept-language: The language currently set by the browser
    • Connection: Type of link between browser and server
    • Cookies: Any cookie that is set on the current page
    • Host: The domain of the page where the request was made
    • Referer: URI of the issuing request page
    • User-agent: User agent string for browser

The following image is a screenshot of the network under my Chrome developer tool, which you can refer to:

We can also set the custom request header information through the setRequestHeader () method. This method receives two parameters: the name of the header field and the value of the header field. And we have to call the setRequestHeader () method after the open () method before the Send () method. Examples are as follows:

1234 varxhr=newXMLHttpRequest();xhr.open("get","example.php",true);xhr.setRequestHeader("myHeader","myValue");xhr.send(null);

It is important to note that the name of the header field passed in here is best customized, rather than using the name of the field that the browser sends normally, otherwise it may affect the browser's response. (because some browsers allow developers to override the default header information, and some browsers do not allow developers to override the default header information.)

In addition to adding a custom header field to the request header, we can also get the header field. We can get the response header information by invoking the getResponseHeader () method of the Xhr object and passing in a header field name. You can also call the getAllResponseHeaders () method of the Xhr object to get a long string containing all the header information.

As shown below:

12 varmyHeader=xhr.getResponseHeader("myHeader");varallHeaders=xhr.getAllResponseHeaders();

  

Part V: GET request

Get requests are used to query the server for certain information. Note that the query string (name/value pair) is sent in the URL of the GET request. However, there are times when the problem may occur, that is, the format of the query string is problematic. The name and value of each parameter of the query string must be encoded with encodeuricomponent () before it can be placed at the end of the URL, and all name value pairs must be separated by &. As shown below:

1 xhr.open("get","example.php?name1=value1&name2=value2",true);

The following function can assist in adding a query string to the end of an existing URI:

123456789 function   ; Adduriparam (url,name,vaule) {      url+= (Url.indexof ( "?" ) ==-1? "?" : & );      url+=encodeuricomponent (name) + "=" +encodeuricomponent (value);      return   url; } var   url= "Example" ; url=adduriparam (URL, "name" , "ZZW" ); url=adduriparam (URL, "Sex" , "male" ); Xhr.open ( "Get" , URL, false );

In fact, the first sentence in the function is to first determine if there is no query string after the URL, if not, add it? , if any, add &, so the final URL is "Example.php?name=zzw&sex=male".

Also, note the need for GET requests:

    • Get requests can be cached
    • Get requests remain in history
    • Get requests can be bookmarked (because the query string is in the URL)
    • Get requests should not be used when handling sensitive data (because the query string is exposed and can be seen by anyone)
    • Get requests have a length limit, beyond the maximum length after the general cannot be submitted, more see here
    • Get requests should only be used to retrieve data

Part VI: POST request

  Post requests are used only as frequently as get requests, and are typically used to send data that should be saved to the server. Note that the query string (name/value pair) is sent in the HTTP message body of the POST request. The GET request is not. The body of a POST request can contain a lot of data, and is not limited in format.

By default, the server does not treat the POST request and submit the Web form requests equally, so we can try the Xhr object and mimic the form submission: first set the Content-type header information to application/ X-www-form-urlencoded, it also mimics the type of content when the form was submitted (like one!). )。 then you need to create a string in the appropriate format, the format of the post data and the format of the query string, if you need to serialize the data of the form in the page, and send it to the server via XHR, use the serialize () function to create the string. Here are two examples:

  

123 xhr.open("POST","example.php",true);xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");xhr.send("fname=Bill&lname=Gates");

Here we do not serialize the string.

1234 xhr.open("POST","example.php",true);xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");varform=document.getElementById("user-info");xhr.send(serialize(form));

Here we use the Serialize () function for serialization.

Also, be aware of Post requests:

    • Post requests are not cached
    • Post requests are not persisted in browser history
    • The POST request cannot be bookmarked (because the sent string does not appear in the URL)
    • POST request has no requirement for data length

 

What is the difference between a POST request and a GET request?

Part VII: Homologous strategy

One of the main limitations of Ajax communication through XHR is the cross-domain security policy, also known as homologous policy. So what is homologous strategy?

Homologous policy, which is a well-known security policy presented by Netscape, by default, the XHR object can only access resources that reside in the same domain as the page containing his, and this security policy prevents certain malicious behavior. Now all JavaScript-enabled browsers use this strategy, which can prevent malicious behavior, such as a site is a bank, if the user after landing, other sites can read a site's cookies, then other sites can do whatever they like. However, implementing a reasonable cross-domain request is also critical for developing applications for certain browsers. I'll cover the knowledge of cross-domain resource sharing in subsequent articles. Only the same-origin policy is described here.

The so-called homologous means: protocol, domain name and port are the same.

For example, http://www.cnblogs.com/dir/page.html this website.

Protocol:/HTTP

Domain Name: www.cnblogs.com

PORT: 80 (default port can be omitted).

The same origin for this URL is as follows:

    • Http://www.cnblogs.com/cat/index.html (homologous)
    • Http://cnblogs.com/dir/page.html (different source-domain name is different)
    • Https://cnblogs.com/dir/page.html (different source-protocol different)
    • Http://www.cnblogs.com:81/dir/page.html (different source-port different)

Part VIII: Application

1. Use of native Ajax

The results in the console are as follows:

2. Use of Ajax in jquery

  

His choice of the road, on his knees to take it out.

 

The beauty of JavaScript Ajax ~

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.