Home > Web Front-end > JS Tutorial > What are the basic processes of ajax? Detailed analysis of the basic process of ajax (with examples)

What are the basic processes of ajax? Detailed analysis of the basic process of ajax (with examples)

寻∝梦
Release: 2018-09-10 16:17:17
Original
1239 people have browsed it

This article mainly talks about the usage process of ajax, as well as the memory method of ajax. Now let’s read this article together

AJAX usage process and Memory method

This memory method may not be good. If you feel it is not suitable for you, you can think of another one.

  1. new XMLHttpRequest(); --- Received a new express delivery

  2. open('Methor',url,true); --- You can't wait to open

  3. send(); --- I found something wrong with your item and sent it back

  4. function onload(){} --- The seller handles your express delivery

  5. responseText --- After processing, the courier will be returned to you

To completely implement an AJAX asynchronous call and partial refresh, the following steps are usually required:

(1) Create an XMLHttpRequest object, that is, create an asynchronous call object.

(2) Create a new HTTP request, and specify the method, URL and verification information of the HTTP request

                                                                                                                        use using it             ‐ ’ ’ s ’ s ‐ ‐ ‐ ‐ being set up to respond to HTTP request status changes.                                                                        . # (6) Use JavaScript and DOM to achieve partial refresh.

1. Create an XMLHttpRequest object

Different browsers use different asynchronous calling objects. In IE Asynchronous calls in browsers use the XMLHttpRequest object in the XMLHTTP component, while in Netscape and Firefox browsers, the XMLHttpRequest component is used directly. Therefore, the way to create XMLHttpRequest objects in different browsers is different.

The way to create XMLHttpRequest objects in IE browser is as follows: var xmlHttpRequest = new ActiveXObject(" Microsoft.

Since it is impossible to determine what browser the user is using, it is best to add both of the above methods when creating an XMLHttpRequest object. As shown in the following code:

<html>
<head>
    <title>创建XMLHttpRequest对象</title>
    <script language = "javascript" type = "text/javascript">
        <!--
        var xmlHttpRequest;  //定义一个变量,用于存放XMLHttpRequest对象
        function createXMLHttpRequest()    //创建XMLHttpRequest对象的方法
        {
            if(window.ActiveXObject)   //判断是否是IE浏览器
            {
                xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");  //创建IE浏览器中的XMLHttpRequest对象
            }
            else if(window.XMLHttpRequest)    //判断是否是Netscape等其他支持XMLHttpRequest组件的浏览器
            {
                xmlHttpRequest = new XMLHttpRequest();  //创建其他浏览器上的XMLHttpRequest对象
            }
        }
        -->
    </script>
    createXMLHttpRequst();   //调用创建对象的方法
</head>
<body>
</body>
</html>
Copy after login

"if(window. ActiveXObject)" is used to determine whether to use IE browser. ActiveXOject is not a standard property of Windows objects, but a property exclusive to IE browser, which can be used to determine whether the browser supports ActiveX controls. Usually only IE browser or Only browsers with IE as the core can support ActiveX controls.

"else if(window.XMLHttpRequest)" is a judgment made to prevent some browsers from supporting neither ActiveX controls nor XMLHttpRequest components. .XMLHttpRequest is not a standard attribute of the window object, but it can be used to determine whether the browser supports the XMLHttpRequest component.

If the browser neither supports ActiveX controls nor XMLHttpRequest components, then it will not Variable assignment.

2. Create HTTP request

After creating the XMLHttpRequest object, you must create an HTTP request for the XMLHttpRequest object to illustrate the XMLHttpRequest Where does the object get the data from? It can usually be data in the website or data in other local files.

To create an HTTP request, you can use the open() method of the XMLHttpRequest object. The syntax code is as follows Display:

   XMLHttpRequest.open(method,URL,flag,name,password)
Copy after login
The parameters in the code are explained as follows:

method: This parameter is used to specify the HTTP request method. There are five methods: get, post, head, put, and delete. , commonly used methods are get and post.

URL: This parameter is used to specify the URL address of the HTTP request, which can be an absolute URL or a relative URL.

Flag: This parameter is optional and the parameter value is Boolean. This parameter is used to specify whether to use asynchronous mode. true indicates asynchronous mode, false indicates synchronous mode, and the default is true.

Name: This parameter is optional and is used to enter the user name. This parameter must be used if the server requires authentication.

Password: This parameter is optional and is used to enter the password. This parameter must be used if the server requires authentication. You can usually use the following code to access the contents of a website file.

      xmlHttpRequest.open("get","http://www.aspxfans.com/BookSupport/JavaScript/ajax.htm",true);

                      or use the following code to access a Local file content:

xmlHttpRequest.open("get","ajax.htm",true);

Note: If the HTML file is placed on a Web server, the JavaScript security mechanism in the Netscape browser does not allow communication with hosts other than this machine. In other words, using the open() method can only open files on the same server as the HTML file. There is no such restriction in IE browser (although files on other servers can be opened, there will also be a warning).

3. Set the function to respond to HTTP request status changes

​​​ After creating the HTTP request, you should You can then send the HTTP request to the web server. However, the purpose of sending an HTTP request is to receive data returned from the server. Starting from the creation of the XMLHttpRequest object, to sending data, receiving data, and the XMLHttpRequest object will go through the following 5 states.

Uninitialized state. After creating the XMLHttpRequest object, the object is in an uninitialized state. At this time, the XMLHttpRequest object ##readyStateThe attribute value is 0. (If you want to see more, go to the PHP Chinese website AJAX Development Manual column to learn)

Initialization state . After creating the XMLHttpRequest object, use the open() method to create HTTP When requested, the object is in an initialized state. At this time, the XMLHttpRequest object's readyState attribute value is 1.

Sending data status. After initializing the XMLHttpRequest object, when using the send() method to send data, the object is in the state of sending data. status. At this time, the readyState attribute value of the XMLHttpRequest object is 2.

Receive data status. WebAfter the server receives the data and processes it, it sends the returned result to the client. At this time, the XMLHttpRequest object is in the state of receiving data, and the readyState of the XMLHttpRequest The attribute value is 3.

Complete status. XMLHttpRequestAfter the object completes receiving data, it enters the completion state. At this time, XMLHttpRequest#readyState of the object The attribute value is 4. At this time, the received data is stored in the memory of the client computer and can be obtained using the responseText attribute or the responseXml attribute. data.

        只有在XMLHttpRequest对象完成了以上5个步骤之后,才可以获取从服务器端返回的数据。因此,如果要获得从服务器端返回的数据,就必须要先判断XMLHttpRequest对象的状态。

       XMLHttpRequest对象可以响应readystatechange事件,该事件在XMLHttpRequest对象状态改变时(也就是readyState属性值改变时)激发。因此,可以通过该事件调用一个函数,并在该函数中判断XMLHttpRequest对象的readyState属性值。如果readyState属性值为4则使用responseText属性或responseXml属性来获取数据。具体代码如下所示:

  //设置当XMLHttpRequest对象状态改变时调用的函数,注意函数名后面不要添加小括号

       xmlHttpRequest.onreadystatechange = getData;

       //定义函数

       function getData(){

              //判断XMLHttpRequest对象的readyState属性值是否为4,如果为4表示异步调用完成

              if(xmlHttpRequest.readyState == 4) {

                          //设置获取数据的语句

               }

        }
Copy after login

4、设置获取服务器返回数据的语句

       如果XMLHttpRequest对象的readyState属性值等于4,表示异步调用过程完毕,就可以通过XMLHttpRequest对象的responseText属性或responseXml属性来获取数据。

       但是,异步调用过程完毕,并不代表异步调用成功了,如果要判断异步调用是否成功,还要判断XMLHttpRequest对象的status属性值,只有该属性值为200,才表示异步调用成功,因此,要获取服务器返回数据的语句,还必须要先判断XMLHttpRequest对象的status属性值是否等于200,如以下代码所示:

if(xmlHttpRequst.status == 200){
       //使用以下语句将返回结果以字符串形式输出
                document.write(xmlHttpRequest.responseText);
                //或者使用以下语句将返回结果以XML形式输出
                //document.write(xmlHttpRequest.responseXML);

}
Copy after login

       注意:如果HTML文件不是在Web服务器上运行,而是在本地运行,则xmlHttpRequest.status的返回值为0。因此,如果该文件在本地运行,则应该加上xmlHttpRequest.status == 0的判断。

        通常将以上代码放在响应HTTP请求状态变化的函数体内,如以下代码所示:     

  //设置当XMLHttpRequest对象状态改变时调用的函数,注意函数名后面不要添加小括号

       xmlHttpRequest.onreadystatechange = getData;

       //定义函数

       function getData()
       {
               //判断XMLHttpRequest对象的readyState属性值是否为4,如果为4表示异步调用完成
                if(xmlHttpRequest.readyState==4)
                {
                       //设置获取数据的语句
                       if(xmlHttpRequest.status == 200 || xmlHttpRequest.status == 0)
                       {
                               //使用以下语句将返回结果以字符串形式输出
                               document.write(xmlHttpRequest.responseText);
                               //或者使用以下语句将返回结果以XML形式输出
                               //docunment.write(xmlHttpRequest.responseXML);
                       }
                }
       }
Copy after login


5、发送HTTP请求

       在经过以上几个步骤的设置之后,就可以将HTTP请求发送到Web服务器上去了。发送HTTP请求可以使用XMLHttpRequest对象的send()方法,其语法代码如下所示:

       XMLHttpRequest.send(data)

       其中data是个可选参数,如果请求的数据不需要参数,即可以使用null来替代。data参数的格式与在URL中传递参数的格式类似,以下代码为一个send()方法中的data参数的示例:

       name=myName&value=myValue

       只有在使用send()方法之后,XMLHttpRequest对象的readyState属性值才会开始改变,也才会激发readystatechange事件,并调用函数。(想看更多就到PHP中文网AJAX开发手册栏目中学习)

6、局部更新

       在通过Ajax的异步调用获得服务器端数据之后,可以使用JavaScript或DOM来将网页中的数据进行局部更新。常用的局部更新的方式有以下3种:

       ⑴表单对象的数据更新

       表单对象的数据更新,通常只要更改表单对象的value属性值,其语法代码如下所示:

        FormObject.value = "新数值"

        有关表单对象的数据更新的示例如以下代码所示:

  //设置当XMLHttpRequest对象状态改变时调用的函数,注意函数名后面不要添加小括号
       xmlHttpRequest.onreadystatechange = getData;
       //定义函数
      function getData()
       {
               //判断XMLHttpRequest对象的readyState属性值是否为4,如果为4表示异步调用完成
                if(xmlHttpRequest.readyState==4)
                {
                       //设置获取数据的语句
                       if(xmlHttpRequest.status == 200 || xmlHttpRequest.status == 0)
                       {
                               //使用以下语句将返回结果以字符串形式输出
                               document.write(xmlHttpRequest.responseText);
                               //或者使用以下语句将返回结果以XML形式输出
                               //docunment.write(xmlHttpRequest.responseXML);
                       }
                }
       }
Copy after login

        ⑵IE浏览器中标签间文本的更新

        在HTML代码中,除了表单元素之外,还有很多其他的元素,这些元素的开始标签与结束标签之间往往也会有一点文字(如以下代码所示),对这些文字的更新,也是局部更新的一部分。

 	<p>文字</p>
       <span>文字</span>
       <p>文字</p>
       <label>文字</label>
       <b>文字</b>
       <i>文字</i>
Copy after login

   在IE浏览器中,innerText或innerHTML属性可以用来更改标签间文本的内容。其中innerText属性用于更改开始标签与结束标签之间的纯文本内容,而innerHTML属性用于更改HTML内容。如以下代码所示:   

 <html>
<head>
<title>局部更新</title>
<script language="javascript" type="text/javascript">	function changeData(){	    myp.innerText = "更新后的数据";	}
</script>
</head>
<body>	<p id="mype">原数据</p>	<input type="button" value="更新数据" onclick="changeData()">
</body>
</html>
Copy after login

       ⑶DOM技术的局部刷新

       innerText和innerHTML两个属性都是IE浏览器中的属性,在Netscape浏览器中并不支持该属性。但无论是IE浏览器还是Netscape浏览器,都支持DOM。在DOM中,可以修改标签间的文本内容。

       在DOM中,将HTML文档中的每一对开始标签和结束标签都看成是一个节点。例如HTML文档中有一个标签如下所示,那么该标签在DOM中称之为一个“节点”。

      

原数据

       在DOM中使用getElementById()方法可以通过id属性值来查找该标签(或者说是节点),如以下语句所示:

       var node = document.getElementById("myp");

       注意:在一个HTML文档中,每个标签中的id属性值是不能重复的。因此,使用getElementById()方法获得的节点是唯一的。

       在DOM中,认为开始标签与结束标签之间的文本是该节点的子节点,而firstChild属性可以获得一个节点下的第1个子节点。如以下代码可以获得

节点下的第1个子节点,也就是

标签与

标签之间的文字节点。

      node.firstChild

      注意,以上代码获得的是文字节点,而不是文字内容。如果要获得节点的文字内容,则要使用节点的nodeValue属性。通过设置nodeValue属性值,可以改变文字节点的文本内容。完整的代码如下所示。   

<html>
<head>
<title>局部更新</title>
<script language="javascript" type="text/javascript">
                         <!--
                                   function changeData()
                                   {
                                             //查找标签(节点)
                                             var node = document.getElementById("myp");
                                             //在DOM中标签中的文字被认为是标签中的子节点
                                             //节点的firstChild属性为该节点下的第1个子节点
                                             //nodeValue属性为节点的值,也就是标签中的文本值
                                             node.firstChild.nodeValue = "更新后的数据";
                                  }
                         -->
                         </script>
</head>
</html>
Copy after login

      注意:目前主流的浏览器都支持DOM技术的局部刷新。

7、完整的AJAX实例

 <html>

                <head>

                           <title>AJAX实例</title>

                           <script language="javascript" type="text/javascript">    
                           <!--

                                     var xmlHttpRequest;  //定义一个变量用于存放XMLHttpRequest对象
                                     //定义一个用于创建XMLHttpRequest对象的函数
                                     function createXMLHttpRequest()
                                    {
                                            if(window.ActiveXObject)
                                            {
                                                   //IE浏览器的创建方式
                                                   xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                                            }else if(windew.XMLHttpRequest)
                                           {
                                                  //Netscape浏览器中的创建方式
                                                  xmlHttpRequest = new XMLHttpRequest();
                                            }
                                   }
                                   //响应HTTP请求状态变化的函数
                                   function httpStateChange()
                                   {
                                          //判断异步调用是否完成
                                         if(xmlHttpRequest.readyState == 4)
                                        {
                                                //判断异步调用是否成功,如果成功开始局部更新数据
                                                if(xmlHttpRequest.status == 200||xmlHttpRequest.status == 0)
                                                {
                                                       //查找节点
                                                       var node = document.getElementById("myp");

                                                        //更新数据

                                                        node.firstChild.nodeValue = xmlHttpRequest .responseText;
                                                }
                                                else
                                               {
                                                     //如果异步调用未成功,弹出警告框,并显示出错信息
                                                     alert("异步调用出错/n返回的HTTP状态码为:"+xmlHttpRequest.status + "/n返回的HTTP状态信息为:" + xmlHttpRequest.statusText);
                                               }
                                         }
                                     }
                                    //异步调用服务器段数据
                                   function getData(name,value)
                                  {                   
                                       //创建XMLHttpRequest对象
                                       createXMLHttpRequest();
                                       if(xmlHttpRequest!=null)
                                       {
                                            //创建HTTP请求
                                            xmlHttpRequest.open("get","ajax.text",true)
                                           //设置HTTP请求状态变化的函数
                                            xmlHttpRequest.onreadystatechange = httpStateChange;
                                           //发送请求
                                          xmlHttpRequest.send(null);
                                        }
                                  }

                           -->
                          </script>

                </head>

                <body>

                         <p id="myp">原数据</p>

                         <input type = "button" value = "更新数据" onclick = "getData()">

                </body>

       </html>
Copy after login

           本篇文章到这就结束了(想看更多就到PHP中文网AJAX使用手册栏目中学习),有问题的可以在下方留言提问。

The above is the detailed content of What are the basic processes of ajax? Detailed analysis of the basic process of ajax (with examples). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template