Write Ajax with native JavaScript

Source: Internet
Author: User

Native JS writing Ajax is like calling

Call 4 steps below
1. Take out your phone
2. Dialing
3. Talk
4. Listen to each other's words

Ajax is also divided into 4 steps below
1. Creating an Ajax Object
2. Connect to the server
3. Send a request (tell the server what file I want)
4. Receive return value

Here is the native JS write Ajax specific wording

<script>window.onload=function () {var obtn = document.getElementById ("btn1"); Obtn.onclick = function () {//1. Create Ajax objects//compatible with non-IE6 browsers only, run on IE6 browser prompts are not defined//var Oajax = new Xmlhtt                Prequest ();//This is the actual Ajax request//alert (Oajax);        IE6 browser under the following method to write, but in other browsers can not be used, will error.        var oajax = new ActiveXObject ("Microsoft.XMLHTTP");                alert (Oajax); In view of the above problems, you can take the following method to resolve, using if to determine whether the IE6 browser if (window. XMLHttpRequest)//If there is XMLHttpRequest, it is a non-IE6 browser.        () The reason for adding window is described below.            {var oajax = new XMLHttpRequest ();//Create Ajax Object} else//If there is no XMLHttpRequest, it is IE6 browser { var oajax = new ActiveXObject ("Microsoft.XMLHTTP");//ie6 browser creates Ajax object}//2. Connect to Server//open (        method, file name, asynchronous transfer)//method://The mode of transmission is get mode or post mode. FileName//Tell the server which file to read//asynchronous Transfer//asynchronous: Do one thing at a time//synchronous: Multiple things together//But JS inside synchronous and asynchronous and                The reality of synchronous async is reversed. //sync: Do one thing at a--asynchronous: Multiple things together//ajax is inherently used to do asynchronous Oajax.open ("GET", "A.txt?t= ' +new Date ()." Ge                Ttime () ", true);//plus t= ' +new Date (). GetTime ()" is designed to eliminate the cache, each time the value of T is different.                3. Send request Oajax.send (); 4. onReadyStateChange oajax.onreadystatechange=function () {//oaj is called when receiving a return//client and server side interaction                Ax.readystate//browser and server, to which step.                0-> (uninitialized): The Open () method has not been called yet.                1-> (load): The Send () method is called and the request is being sent.                2-> loading complete): The Send () method completes and all responses have been received.                3-> (parsing): The response content is being parsed.            4-> (complete): Response content resolution is complete and can be called on the client.                    if (oajax.readystate==4) {if (oajax.status==200)//is judged successful, if 200, it represents success { Alert ("Success" +oajax.responsetext);//Read A.txt file success will pop up successfully.                The appended oajax.responsetext will output the contents of the A.txt text} else {alert ("failed");    }            }        }; }};/*If the above if need some window reason//js variables and properties var a = 12;alert (a);//Page Popup 12 is normal, but the actual output is the following wording, is the window, but window can save the province. alert (WINDOW.A);//output is the same as Window.alert (WINDOW.A);//This global variable is actually a property of Winow. If you do not define a variable a, output Aalert (a) directly as follows (a)//the system will error, not undefind, because the variable a is not defined. alert (WINDOW.A);//If this is the case, the system will not error, will show Undefind. The reason for this is because direct write a does not find a from the root, and the front plus window simply cannot find the property a of window. */</script>

However, you can not write so much code every time with Ajax, to encapsulate this Ajax code, easy to use.

Encapsulating Ajax

Finally, encapsulate the code and wrap it up to add a parameter URL to the function. The parameter is to replace the file name to be read function Ajax (URL,FNSUCC) {    if (window. XMLHttpRequest)        {            var oajax = new XMLHttpRequest ();        }        else        {            var oajax = new ActiveXObject ("Microsoft.XMLHTTP");//ie6 browser creates Ajax object        }        oajax.open ("GET", url , true);//pass over the parameters to be read.        oajax.send ();        Oajax.onreadystatechange=function ()        {            if (oajax.readystate==4)            {                if (oajax.status==200)                {                    fnsucc (oajax.responsetext);//Successful Call this method                }                else                {                    if (fnfiled)                    {                        Fnfield (Oajax.status);}}}        ;}

To encapsulate an Ajax call

<script src= "New_ajax.js" ></script>//reference encapsulated Ajax file <script>window.onload=function () {    var oBtn = document.getElementById ("btn1");    Obtn.onclick = function ()    {        ajax (' A.txt ', function (str) {//reads the contents of the A.txt file                alert (str);//content to be read output            })                }}; </script>

Write Ajax with native JavaScript

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.