Ajax principle-XMLHttpRequest object meaning of native JS __php

Source: Internet
Author: User
Tags string format
Ajax Principle-the XMLHttpRequest object meaning of native JS

Ajax is shorthand for asynchronous JavaScript + XML, a technology that can request additional data from the server without uninstalling the page, bringing a good user experience. The core of Ajax technology is the XMLHttpRequest (XHR) object, XHR provides a smooth interface for sending requests to the server and analyzing the server response, and it is possible to get more information from the server House in an asynchronous manner without refreshing the page. Use XML objects to get new data and then insert new data into the page through the DOM.

One: XMLHttpRequest objects
IE5 is the first browser to introduce XHR objects, XHR objects are implemented through an ActiveX object in the MSXML library. Therefore, in IE may encounter three different versions of the XHR objects: Msxml2.xmlhttp, msxml2.xmlhttp.3.0, msxml2.xmlhttp.6.0. For example:

    function createxhr () {
        if (typeof arguments.callee.activeXString!= ' string ') {
            var versions = [' MSXML2. xmlhttp.6.0 ', ' MSXML2. XMLHttp ', ' MSXML2. xmlhttp.3.0 '];
            for (var i=0 i<versions.length; i++) {
                try{
                    new ActiveXObject (versions[i));
                    arguments.callee.activeXString = Versions[i];
                    break;
                catch (e) {
                    console.log (' no ');
        }} return new ActiveXObject (arguments.callee.activeXString);
    }

This function creates the latest version of the Xhr object based on the MSXML libraries available in IE, Ie7firefox, Opera, Chrome, and Safari support native XHR objects, creating XHR objects in these browsers: var xhr = new XMLHttpRequest (), add the version you want to support IE7 and higher, so you can throw away the previously defined function, and use only the native XHR implementation. However, if you have to use an earlier version of IE, you can add support for the native XHR object in this createxhr () function.

 function createxhr () {if (XMLHttpRequest) {return new Xmlhtt
            Prequest ();  else if (ActiveXObject) {if (typeof arguments.callee.activeXString!= ' string ') {var
                    versions = [' msxml2.xmlhttp.6.0 ', ' msxml2.xmlhttp ', ' msxml2.xmlhttp.3.0 ']; for (var i = 0; i < versions.length; i++) {try {new ActiveXObject (
                            Versions[i]);
                            arguments.callee.activeXString = Versions[i];
                        Break
                        catch (E) {console.log (' no ');
            }} return new ActiveXObject (arguments.callee.activeXString);
            else {throw new Error ("No XHR object Available"); }
        }

Second: The use of XHR.
When using the Xhr object, the first method to invoke is open (), for example:

Xhr.open (' Get ', ' somfile.txt ', false);
Xhr.send (NULL);

Here Send () method, if you do not need to send data to the request body, it is best to pass the null parameter, because this parameter is necessary for some browsers.
Because of this response synchronization, the JS code will wait until the server responds and then continue execution. When a response is received, the response data automatically populates the properties of the Xhr object, with the associated properties as follows:
ResponseText: A text that is returned as a response subject;
Responsexml: As the corresponding content type is Text/xml or Application/xml, this property will hold the XMLDOM document containing the corresponding data;
Status: the corresponding HTTP status;
Description of the Statustext:http status.
After receiving the response, the first step is to check the Status property and, when Xhr.status is 200, to accept the success and, when Xhr.status is 304, to indicate that the requested resource has not been modified, and that the cached version in the browser can be used directly. The code is as follows:

                if (xhr.readystate = = 4 && (xhr.status = = | | xhr.status = 304)) {
                    document.getElementById ("mydiv"). Innerh TML = Xhr.responsetext;
                } else {
                    "Request was unsuccessful:" + Xhr.status;
                }

  Asynchronous Usage
In most cases, we are sending an asynchronous request to allow JavaScript to continue the current active phase. Take the following values:
0: Uninitialized, the Open () method has not been invoked.
1. Start up. The open () method has been called, but the Send () method has not been invoked.
2. Send, has called Send () method, to receive the response.
3. Accept. Partial response data has been accepted.
4. Complete. All data that accepts the response and can be used on the client.
Whenever the value of the ReadyState property changes, a onreadystatechange event is triggered. The code is as follows:

        function Loadxmldoc () {
            var xhr = createxhr ();
            Xhr.onreadystatechange = function () {
                console.log (XHR)
                if (xhr.readystate = = 4 && (xhr.status = = | | xh R.status = = 304)) {
                    document.getElementById ("mydiv"). InnerHTML = Xhr.responsetext;
                } else {
                    "Request was Unsuccessful: "+ xhr.status;
                }
            }

            " Xhr.open (' Get ', ' somfile.txt ', true);
            Xhr.send (null);
        }

Also, before receiving a response, you can call the Abort () method and cancel the asynchronous request: Xhr.abort ();
Three: Set the custom request header with setRequestHeader
This method takes two parameters: the name of the header field and the value of the header field. After the server receives this custom header information, it can perform subsequent operations and is recommended for use, or it may affect the server's response.

        function Loadxmldoc () {
            var xhr = createxhr ();
            Xhr.onreadystatechange = function () {
                if (xhr.readystate==4 | | xhr.status==200) {
                    document.getElementById (" Mydiv "). InnerHTML = Xhr.responsetext;
                } else{
                    "Request was unsuccessful:" + Xhr.status;
                }}
            Xhr.open (' Get ', ' somfile.txt ', true);
            Xhr.setrequestheader (' MyHeader ', ' myvalue ');
            Xhr.send (null);
        }

four: Get request
For XHR, the query string at the end of the URL of the incoming open () method must be encoded correctly.
An error that often occurs with get requests is that there is a problem with the query string format. The name and value of each parameter in the query string must be encoded using encodeURIComponent () before it can be placed at the end of the URL, and the name-value pair must be split by & as shown below:

<body> Name: <input type= "text" name= "name" > <br> book: <input type= " Text "name=" book "> <br> <input type=" button "id=" Submit "value=" Submit "> </body> ; script type= "Text/javascript" > Function createxhr () {if (XMLHttpRequest) {return new XMLHttp
        Request ();
        else {return new ActiveXObject (' microsoft.xmlhttp ');
    }
    }; Get method, key value pair processing function addurlparam (URL, name, value) {url = = (Url.indexof ('? ') = = 1?
        '? ': ' & ');
        URL + encodeuricomponent (name) + ' = ' + encodeuricomponent (value);
    return URL; ///Simulate form submission function Formsubmit () {//Get text box node var names = Document.queryselectorall (' input ') [0].val
        Ue
        var books = Document.queryselectorall (' input ') [1].value;
        Console.log (names) var xhr = CREATEXHR (); Xhr.onreadystatechange = function () {if(xhr.readystate = 4 | | xhr.status = 200)
        {Console.log (Xhr.responsetext)}}
        var url = ' 01.php ';
        Add parameter URL = addurlparam (URL, ' name ', names);
        url = addurlparam (URL, ' book ', books);
        Console.log (URL)//initialization request Xhr.open ("Get", url, True);
    Xhr.send (NULL);
    var sub = document.getElementById (' Submit ');
    Sub.onclick = function () {formsubmit (); } </script>

V: Post request
The server is not the same as the POST request, therefore, the server side must have a program to read the sent over the raw data, and to resolve the useful parts: first, the Content-type header information set to Application/x-www-form-urlencoded, That is, the type of content when the form is submitted, followed by the creation of a string in the appropriate format, which requires the XMLHTTPREQUEST2-level defined formdata type if the post data needs to be serialized for the server to be easily processed. That

var data = new FormData ();
Data.append (' name ', ' Bangbang ');
... ...
Xhr.open (' Post ', ' 02.php ', true);
var form = document.getElementById (' Form1 ');
Xhr.send (new FormData (form));

Of course, we can use the custom serialize () function to handle.
For example:

<body> <form id= "Form1" > Name: <input type= "text" name= "name" > <br> bo OK: <input type= "text" name= "book" > <br> <input type= "button" id= "Submit" Value= "Su Bmit "> </form> <div id=" Con "></div> </body> <script type=" Text/javascript ">/ /serialization Functions function serialize (form) {var parts = [], field = NULL, option, OP
        TValue;
            for (var i = 0; i < form.elements.length i++) {field = Form.elements[i]; Switch (field.type) {case ' Select-one ': Case "select-multiple": if (field.name.le Ngth) {for (var j = 0; J < Field.options.length; J + +) {option = Field.opt
                        IONS[J];
                            if (option.selected) {optvalue = '; if (optioin.hasattributE) {Optvalue = (Option.hasattribute (' value ')? option.value:option.text);  else {Optvalue = (option.attributes[' value '].specified? Option.value:
                            Option.text);
                        } parts.push (encodeURIComponent (field.name) + ' = ' + encodeURIComponent (optvalue));
            }} break;
            Case undefined://field set case ' file '://File input case ' submit ':///Submit button case ' reset '://reset button
            Case ' button '://custom button break;
                Case ' Radio '://radio button case ' checkbox '://check box if (!field.checked) {break; } default:if (Field.name.length) {Parts.push (encodeuricom
      Ponent (field.name) + ' = ' + encodeURIComponent (field.value));          }} return Parts.join (' & ');
        function Createxhr () {if (XMLHttpRequest) {return new XMLHttpRequest ();
        else {return new ActiveXObject (' microsoft.xmlhttp ');

    }
    };
        function Formsubmit () {var xhr = createxhr ();
        Console.log (xhr.readystate);
                    Xhr.onreadystatechange = function () {if (xhr.readystate = 4 | | xhr.status = = 200) {
                    Console.log (Xhr.responsetext);
                document.getElementById (' con '). InnerHTML = Xhr.responsetext;
        }///Initialize Request Xhr.open ("post", ' 02.php ', true);
        Xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
        var form = document.getElementById (' Form1 ');
        Console.log (Form) (serialize);
    Xhr.send (Form) (serialize);
    var sub = document.getElementById (' Submit ');
Sub.onclick = function () {        Formsubmit (); } </script>
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.