Ajax Madness Handout

Source: Internet
Author: User

Ajax:async JavaScript and XML asynchronous JS and XML

AJAX is a technique for creating fast, Dynamic Web pages. AJAX enables Web pages to be updated asynchronously by exchanging small amounts of data in the background with the server. This means that you can update a part of a webpage without reloading the entire page. Traditional Web pages (without AJAX) if you need to update the content, you must reload the entire page surface.

Ajax create four Footwork

We all know that a complete Ajax Dynamic Web page is implemented by:

var New Xmlhttprequest;xhr.open ("Get", "url",truefunction  () {    "code Gose There "; }xhr.send (string);

We will explain the above four steps in detail below.

Ajax-Creating an AjaxXMLHttpRequest Object

XMLHttpRequest is the basis of AJAX.

XMLHttpRequest term abbreviation is XHR, Chinese can be interpreted as extensible Hypertext transfer request.

All modern browsers (ie7+, Firefox, Chrome, Safari, and Opera) have built-in XMLHttpRequest objects. (IE5 and IE6 use ActiveXObject).

XMLHttpRequest is used to exchange data with the server in the background. This means that you can update a part of a webpage without reloading the entire page.

To handle all modern browsers, including IE5 and IE6, check whether the browser supports XMLHttpRequest objects. If supported, the XMLHttpRequest object is created. If not supported, create the ActiveXObject::

functioncreatexhr () {varXHR =NULL; if(window. XMLHttpRequest) {XHR=NewXMLHttpRequest; } Else {            Try{XHR=NewActiveXObject ("Microsoft.XMLHTTP"); } Catch(e) {Try{XHR=NewActiveXObject ("Msxml2.xmlhttp"); }                Catch(e) {                }            }        }        returnXHR; }
var xhr = createxhr ();

Know the CREATEXHR () method above every time you create a Xhr object, the Createxhr method will be executed again. Since the first time we implemented it we knew which new method was supported under the browser. But the second time you execute the CREATEXHR method, you still need to re-execute it all over again. This obviously increases the overhead of the system. So we can programmatically return the new method that supports the browser in a lazy way, so that you don't need to execute all the code every time you execute it.

The optimized code code is as follows:

functioncreatexhr () {varXHR =NULL, Flag=false, arr= [                    function () {                        return NewXMLHttpRequest; },                    function () {                        return NewActiveXObject ("Microsoft.XMLHTTP"); },                    function () {                        return NewActiveXObject ("Msxm12.xmlhttp"); }                ];  for(vari = 0; i < arr.length; i++) {                varCURFN =Arr[i]; Try{XHR=CURFN (); //The loop gets the method without error: This method is what I want, the next time we execute this method directly, this requires me to rewrite the CREATEXHR as the method of this loop (after completion do not need to judge the following, directly exit the loop can be)CREATEXHR =CURFN; Flag=true;  Break; } Catch(e) {//error occurred while executing the method of this loop: Continue with Next loop                }                if(!flag) {                    Throw NewError ("Your browser is not a support ajax,please change your browser,try again!"); }                            }            returnXHR; }
var xhr = createxhr ();
AJAX-Sending requests to the server

The XMLHttpRequest object is used to exchange data with the server.

When all your pages are loaded, the client requests the data through the XMLHttpRequest object to the server, and after the server accepts the data and processes it, it feeds back the data to the client.

To send the request to the server, we use the open () and send () methods of the XMLHttpRequest object:

Xhr.open (Method,url,async); xhr.send (string);
    • Specifies the type of request, the URL, and whether the request is processed asynchronously.

Open (method,url,async)

method: type of request; GET or POST

URL: The location of the file on the server, which can be any type of file

Async: True (asynchronous) or false (synchronous)

    • The async parameter of the open () method must be set to True if the XMLHttpRequest object is to be used for AJAX. Because when set to False (that is, synchronization), JavaScript waits until the server responds in readiness to continue execution. If the server is busy or slow, the application hangs or stops.

When set to True, JavaScript does not have to wait for the server to respond, but instead:

Executes additional scripts while waiting for the server to respond.

The response is processed when the response is ready.

    • Send (string)

Sends the request to the server.

string: For POST requests only, the Send method can also be passed without arguments, indicating that no request data is sent to the server

AJAX-ServerResponsebecause the HTTP response is sent by the server and the response takes time (such as slow speed), we need to listen to the status of the server's response before it can be processed. gets the response from the server, using the ResponseText or Responsexml property of the XMLHttpRequest object. -The Xhr.responsetext property is the response data that gets the string form-The Xhr.responsexml property is to get the response data in the form of XMLAJAX-onreadystatechange Events

When a request is sent, the client needs to determine when the request will be completed, so the XMLHttpRequest object provides a onreadystatechange event mechanism to capture the state of the request and then implement the response.

When a request is sent to the server, we need to perform some response-based tasks. The onreadystatechange event is triggered whenever the readystate changes. The ReadyState attribute holds state information for XMLHttpRequest.

The following are three important properties of the XMLHttpRequest object:

    • Xhr.onreadystatechange

The function (or function name) is called whenever the ReadyState property is changed. onReadyStateChange

    • Xhr.readystate

The state of being xmlhttprequest. Vary from 0 to 4.

The 0:unset request was not initialized and the open () was not called.

The 1:opened request has been established, but has not yet been sent, open () has been called, and send () has not been called.

The 2:header_received request has been sent and the Send () function has been called. Being processed (typically, you can now get the content header from the response).

The 3:loading request is in process, and some of the data in the response is usually available and not fully completed.

The 4:loaded response has completed and the contents of the response body have been successfully returned to the client (parsing completed)

    • Xhr.status:HTTP status code that describes the status of the server response content

The number of/^2\d{2}/(200 or 2) indicates that the content of the response body has been successfully returned


301 Permanent Redirect/permanent transfer
302 Temporary redirect/temporary transfer
304 The content of this fetch is to read the data in the cache


400 the client passed an error to the server's parameters
401 No access
404 The Client Access address does not exist

500 Unknown Server error
503 Server has exceeded load

When ReadyState equals 4 and the status is 200, the response is ready: In the onReadyStateChange event, we specify the task that is performed when the server responds to readiness to be processed.

Write a simple library of Ajax methods

Since each AJAX approach requires writing down the complete Ajax four step, it certainly adds to our workload. Let's write an Ajax method, we just need to call this method to implement the Ajax XMLHttpRequest request.

//Ajax: The public way to implement AJAX requests: When a method passes too many parameter values and is not fixed, we use the object uniform Pass-through method (the parameter values to be passed are first placed in an object's options, and can be passed in together)    functionAjax (Options) {var_default ={URL:"",//the requested addressType: "Get",//How to requestDataType: "JSON",//sets the content format "JSON" (that is, the JSON-formatted object) of the request back. "TXT" is a string or JSON-formatted stringAsync:true,//Whether the request is synchronous or asynchronousData:NULL,//content placed in the request body (POST)Getheaders:NULL,//callback function to execute when readystate===2Success:NULL    //callback function to execute when readystate===4        }         for(varKeyinchoptions) {            if(Options.hasownproperty (key)) {_default[key]=Options[key]; }        }        //if the current request method is get, we need to add a random number at the end of the URL to clear the cache        if(_default[type] = = = "Get") {_deauult[url].indexof ("?") >= 0? _default[url] + = "&": _default[url] + = "?"; _default[url]+= "_=" +Math.random (); }        varXHR =createxhr ();        Xhr.open (_default[type],_default[url],_default[async]); Xhr.onreadystatechange=function () {            if(/^2\d{2}$/. Test (Xhr.status)) {                //to do something in readystate=2, you need to make sure that Ajax is an asynchronous request                if(Xhr.readystate = = 2) {                    if(typeof(_default[getheaders]) = = = "function") {_default[getheaders].call (XHR); }                                    }                if(Xhr.readystate = = 4) {                    varval =Xhr.responsetext; if(_default.datatype = = = "JSON") {Val= "JSON"inchWindow? Json.parse (val): eval ("(" + val + ")"); }                    if(typeof(_default[success]) = = = "function") {_default[success].call (xhr,val); };//_default[success] && _default[success].call (xhr,val);}}} Xhr.send (_default[data]);//content is passed to the requesting principal, but the Open method must use the POST request method}

Ajax Madness Handout

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.