Home  >  Article  >  Web Front-end  >  Ajax usage simple tutorial

Ajax usage simple tutorial

巴扎黑
巴扎黑Original
2017-08-09 14:12:291019browse

Asynchronous interaction and synchronous interaction

  • If you want to talk about Ajax, you have to talk about asynchronous transmission and synchronous transmission.

    • Asynchronous is the value: after the sender sends the data, it does not wait for the receiver to send back a response, and then sends the next data packet.

    • Synchronization refers to the communication method in which the sender sends data and waits for the receiver to send back a response before sending the next data packet.

  • can also be understood as:

    • Asynchronous transmission: Just pass it on. I'll go do my thing. Let me know when the transmission is complete.

    • Synchronous transmission: You are transmitting now, and I will watch you complete the transmission before doing anything else.

What is Ajax?

  • Ajax is considered to be the abbreviation of (Asynchronous JavaScript and Xml).

  • #Now, the technology that allows the browser to communicate with the server without refreshing the current page is called Ajax.

How Ajax works.

  • The core of Ajax is the JavaScript object XmlHttpRequest. This object was first introduced in Internet Explorer 5. It is a technology that supports asynchronous requests. In short, XmlHttpRequest allows you to use JavaScript to make requests to the server and handle the responses without blocking the user.

  • Ajax uses an asynchronous interaction process. Ajax introduces an intermediary between the user and the server, thus eliminating the processing-waiting-processing-waiting shortcomings in the network interconnection process.

  • #The user's browser loads the Ajax engine when executing the task. Ajax engines are written in the JavaScript language and are usually hidden in a hidden framework. It is responsible for compiling the interaction between the user interface and the server.

  • The Ajax engine allows the interaction process between the user and the application software to proceed asynchronously, independent of the communication between the user and the network server. Now, JavaScript can be used to call the Ajax engine instead of generating an HTTP user action. In-memory data editing, page navigation, and data verification can be performed by Ajax without reloading the entire page.

  • Using Ajax can bring visible convenience to Jsp, developers, and end users.

Technology included in Ajax:

  • Ajax is not A new technology is actually a combination of multiple technologies, including JavaScript, XHtml and CSS, Dom, Xml and XmlHttpRequest technologies.

    • Server-side language: The server needs to have the ability to send specific information to the browser. Ajax has nothing to do with server-side languages.

    • #Xml (Extensible Markup Language) is a format for describing data. AJAX programs require some format to pass information between the server and the client, and XML is one of the options.

    • XHTML (eXtended Hypertext Markup Language, using extended hypermedia markup language) and CSS (Cascading Style Sheet, cascading style sheet) standardized rendering.

    • DOM (Document Object Model, Document Object Model) implements dynamic display and interaction.

    • Use the XMLHTTP component XMLHttpRequest object for asynchronous data reading.

    • Use JavaScript to bind and process all data.

##Ajax defects:

  • Ajax is not a perfect technology and has flaws:

    • AJAX is used extensively Javascript and AJAX engines are used, and this depends on browser support. It is only supported by IE5.0 and above, Mozilla1.0, NetScape7 and above. Although Mozilla also supports AJAX, it provides XMLHttpRequest in a different way. Therefore, programs that use AJAX must test compatibility with various browsers.

    • AJAX does not refresh the entire page when updating the page content. Therefore, the back function of the web page is invalid; some users often fail to do so. Know whether the current data is old or has been updated. This requires reminding users that "data has been updated" in an obvious location.

    • The support for streaming media is not as good as FLASH and Java Applet.

##Ajax’s core XMLHttpRequest object:

  • XMLHttpRequest is the object of the XMLHTTP component. Through this object, AJAX can only exchange data with the server like a desktop application, without refreshing the interface every time and handing over the data processing work every time. Let the server do it; this not only reduces the load on the server, but also speeds up the response and shortens the user's waiting time.

  • ##XMLHttpRequest was first implemented in IE5 as an ActiveX component. Not a W3C standard.


  • Create XMLHttpRequest object (the implementation method is not unified due to non-standard):

    • Internet Explorer implements XMLHttpRequest as an ActiveX object.


    • Other browsers (Firefox, Safari, Opera...) implement it as a native JavaScript object.


    • The implementation of XMLHttpRequest on different browsers is compatible, so you can access the properties and methods of the XMLHttpRequest instance in the same way, regardless of this What is the method of instance creation.


  • The initialization code is as follows:

    function   createXmlHttpRequest(){
       var xmlHttp;
       try{    //Firefox, Opera 8.0+, Safari
               xmlHttp=new XMLHttpRequest();
        }catch (e){
               try{    //Internet Explorer
                      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
                }catch (e){
                      try{
                              xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
                      }catch (e){}  
               }
        }
       return xmlHttp;
     }

XMLHttpRequest object method :

  • abort(): Stop the current request.

  • getAllResponseHeader(): Returns all response headers of the HTTP request as key/value pairs.

  • getResponseHeader("headerLabel"): Returns the string value of the specified header.

  • open("method","url"): Create a call to the server. The method parameter can be GET or POST. The url parameter can be a relative url or an absolute url. This method also contains 3 optional parameters.

  • send(content): Send a request to the server.

  • setRequestHeader("label","value"): Set the specified header to the provided value. The open() method must be called before setting any headers.

XMLHttpRequest object properties:

  • onreadystatechange:状态改变的事件触发器。

  • readyState:对象状态:

    • 0=未初始化

    • 1=读取中

    • 2=已读取

    • 3=交互中

    • 4=完成

  • responseText:服务器进程返回数据的文本版本。

  • responseXML:服务器进程返回数据的 兼容DOM的Xml文档对象。

  • status:服务器返回的状态码,如404=“文件未找到”,200=“成功”。

  • statusText:服务器返回的状态文本信息。

发送请求的属性和方法(重要),使用以下3个关键部分:

  • openreadystatechange事件处理函数。

    • 该事件处理函数由服务器触发,而不是用户。

    • 在Ajax执行过程中,服务器会通知客户端当前的通信状态。这依靠更新 XMLHttpRequest 对象的 readyState 来实现。改变 readyState 属性是服务器对客户端连接操作的一种方式。

    • 每次 readyState 属性的改变都会触发 readystatechange事件,这个是核心。

  • open(method, url, asynch)方法。

    • XMLHttpRequest 对象的 open 方法允许程序员用一个Ajax调用向服务器发送请求。

    • method:请求类型,类似 “GET”或”POST”的字符串。若只想从服务器检索一个文件,而不需要发送任何数据,使用GET(可以在GET请求里通过附加在URL上的查询字符串来发送数据,不过数据大小限制为2000个字符)。若需要向服务器发送数据,用POST。

    • 在某些情况下,有些浏览器会把多个XMLHttpRequest请求的结果缓存在同一个URL。如果对每个请求的响应不同,这就会带来不好的结果。把当前时间戳追加到URL的最后,就能确保URL的惟一性,从而避免浏览器缓存结果。

      var url = "GetAndPostExample?timeStamp=" + new Date().getTime();
    • url:路径字符串,指向你所请求的服务器上的那个文件。可以是绝对路径或相对路径。

    • asynch:表示请求是否要异步传输,默认值为true(异步)。指定true,在读取后面的脚本之前,不需要等待服务器的相应。指定false,当脚本处理过程经过这点时,会停下来,一直等到Ajax请求执行完毕再继续执行。

  • send(data)方法。

    • open 方法定义了 Ajax 请求的一些细节。send 方法可为已经待命的请求发送指令。

    • data:将要传递给服务器的字符串。

    • 若选用的是 GET 请求,则不会发送任何数据, 给 send 方法传递 null 即可:request.send(null);

    • 当向send()方法提供参数时,要确保open()中指定的方法是POST,如果没有数据作为请求体的一部分发送,则使用null.

    • 完整的 Ajax 的 GET 请求示例:

      //创建Ajax引擎
      var xmlHttpReq = createXmlHttpRequest();  
                      xmlHttpReq.onreadystatechange=function(){  
                          if(xmlHttpReq.readyState==4){  
                              if(xmlHttpReq.status==200){  
                                  document.getElementById("info").innerHTML=xmlHttpReq.responseText;  
                              }  
                          }  
                      }  
      
      xmlHttpReq.open("post","/webLogic/test_test.do",true);
  • setRequestHeader(header,value):

    • 当浏览器向服务器请求页面时,它会伴随这个请求发送一组首部信息。这些首部信息是一系列描述请求的元数据(metadata)。首部信息用来声明一个请求是 GET 还是 POST。

    • Ajax 请求中,发送首部信息的工作可以由 setRequestHeader完成。

    • 参数header: 首部的名字;  参数value:首部的值。

    • 如果用 POST 请求向服务器发送数据,需要将 “Content-type” 的首部设置为 “application/x-www-form-urlencoded”.它会告知服务器正在发送数据,并且数据已经符合URL编码了。

    • 该方法必须在open()之后才能调用.

    • 完整的 Ajax 的 POST 请求示例:

      var xmlHttpReq = createXmlHttpRequest();
      				xmlHttpReq.onreadystatechange=function(){
      					if(xmlHttpReq.readyState==4){
      						if(xmlHttpReq.status==200){
      							document.getElementById("info").innerHTML=xmlHttpReq.responseText;
      						}
      					}
      				}
      				
      				xmlHttpReq.open("post","/webLogic/test_test.do",true);
      				xmlHttpReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      				xmlHttpReq.send("username="+"德玛"+"&pwd="+"123");

接受--方法和属性介绍:

  • 用 XMLHttpRequest 的方法可向服务器发送请求。在 Ajax 处理过程中,XMLHttpRequest 的如下属性可被服务器更改:

    • 如果服务器返回的是 XML, 那么数据将储存在 responseXML 属性中。

    • 只用服务器发送了带有正确首部信息的数据时, responseXML 属性才是可用的。 MIME 类型必须为 text/xml。

    • XMLHttpRequest 的 responseText 属性包含了从服务器发送的数据。它是一个HTML,XML或普通文本,这取决于服务器发送的内容。

    • 当 readyState 属性值变成 4 时, responseText 属性才可用,表明 Ajax 请求已经结束。

      if(xmlHttpReq.readyState==4){
      						if(xmlHttpReq.status==200){
      							document.getElementById("info").innerHTML=xmlHttpReq.responseText;
      						}
      					}
    • 服务器发送的每一个响应也都带有首部信息。三位数的状态码是服务器发送的响应中最重要的首部信息,并且属于超文本传输协议中的一部分。

    • 常用状态码及其含义:

    • 在 XMLHttpRequest 对象中,服务器发送的状态码都保存在 status 属性里。通过把这个值和 200 或 304 比较,可以确保服务器是否已发送了一个成功的响应

    • 404 没找到页面(not found)

    • 403 禁止访问(forbidden)

    • 500 内部服务器出错(internal service error)

    • 200 一切正常(ok)

    • 304 没有被修改(not modified)(服务器返回304状态,表示源文件没有被修改 )

    • readyState 属性表示Ajax请求的当前状态。它的值用数字代表。

    • 每次 readyState 值的改变,都会触发 readystatechange 事件。如果把 onreadystatechange 事件处理函数赋给一个函数,那么每次 readyState 值的改变都会引发该函数的执行。

    • readyState 值的变化会因浏览器的不同而有所差异。但是,当请求结束的时候,每个浏览器都会把 readyState 的值统一设为 4

    • 0 代表未初始化。 还没有调用 open 方法

    • 1 代表正在加载。 open 方法已被调用,但 send 方法还没有被调用

    • 2 代表已加载完毕。send 已被调用。请求已经开始

    • 3 代表交互中。服务器正在发送响应

    • 4 代表完成。响应发送完毕

    • readyState

    • status

    • responseText

    • responseXML

Ajax的具体使用:

  • AJAX实质上也是遵循Request/Server模式,所以这个框架基本的流程是:

    • responseText:将传回的信息当字符串使用;

    • responseXML:将传回的信息当XML文档使用,可以用DOM处理。 

      function processResponse(){
         if(XMLHttpReq.readyState==4){ //判断对象状态 4代表完成
                 if(XMLHttpReq.status==200){ //信息已经成功返回,开始处理信息
                        document.getElementById("chatArea").value=XMLHttpReq.responseText;
                }
         }
            }
    • 响应需要做什么:

    • 处理响应处理函数都应该做什么。 
        首先,它要检查XMLHttpRequest对象的readyState值,判断请求目前的状态。参照前文的属性表可以知道,readyState值为4的时候,代表服务器已经传回所有的信息,可以开始处理信息并更新页面内容了。如下:
      if (http_request.readyState == 4) {
          // 信息已经返回,可以开始处理
      } else {
          // 信息还没有返回,等待
      }
        服务器返回信息后,还需要判断返回的HTTP状态码,确定返回的页面没有错误。所有的状态码都可以在W3C的官方网站上查到。其中,200代表页面正常。
      if (http_request.status == 200) {
            // 页面正常,可以开始处理信息
      } else {
          // 页面有问题
      }

    • 向服务器发出HTTP请求了。这一步调用XMLHttpRequest对象的open和send方法。     http_request.open('GET', 'http://www.example.org/some.file', true);
           http_request.send(null)

    • 按照顺序,open调用完毕之后要调用send方法。send的参数如果是以Post方式发出的话,可以是任何想传给服务器的内容。

    • 注意:如果要传文件或者Post内容给服务器,必须先调用setRequestHeader方法,修改MIME类别。如下:

    • http_request.setRequestHeader(“Content-Type”,”application/x-www-form-urlencoded”);
          这时资料则以查询字符串的形式列出,作为send的参数,例如:
          name=value&anothername=othervalue&so=on

      //发送请求
      function sendRequest(){
      //获取文本框的值
      var chatMsg=input.value;
      var url="chatServlet.do?charMsg="+chatMsg;
      //建立对服务器的调用
      XMLHttpReq.open("POST",url,true);
      //设置MiME类别,如果用 POST 请求向服务器发送数据,
      //需要将"Content-type" 的首部设置为 "application/x-www-form-urlencoded".
      //它会告知服务器正在发送数据,并且数据已经符合URL编码了。
      XMLHttpReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      //状态改变的事件触发器,客户端的状态改变会触发readystatechange事件,
      //onreadystatechange会调用相应的事件处理函数
      XMLHttpReq.onreadystatechange=processResponse;
      //发送数据
      XMLHttpReq.send(null);
      }
    • 对象初始化

      function   createXmlHttpRequest(){
         var xmlHttp;
         try{    //Firefox, Opera 8.0+, Safari
                 xmlHttp=new XMLHttpRequest();
          }catch (e){
                 try{    //Internet Explorer
                        xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
                  }catch (e){
                        try{
                                xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
                        }catch (e){}  
                 }
          }
         return xmlHttp;
       }
    • 发送请求

    • 服务器接收

    • 服务器响应

    • 客户端接收,返回两种格式:

    • 修改客户端页面内容。

  • 只不过这个过程是异步的。

  • 完整的如下:

    var xmlHttpReq = createXmlHttpRequest();
    				xmlHttpReq.onreadystatechange=function(){
    					//为4表示请求和响应结束
    					if(xmlHttpReq.readyState==4){
    						//200表示响应成功
    						if(xmlHttpReq.status==200){
    							//在div上添加action返回的值
    							document.getElementById("info").innerHTML=xmlHttpReq.responseText;
    						}
    					}
    				}
    				//这是get方式发送数据,中文记得在接受时进行编码
    				xmlHttpReq.open("post","/webLogic/test_test.do?username=aaa",true);
    				//post请求时一定要加这个请求头
    //				xmlHttpReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    //				xmlHttpReq.send("username="+"德玛"+"&pwd="+"123");//这是post请求的发送数据方法
    				//get方式send(null),写了也没用
    				xmlHttpReq.send(null);

The above is the detailed content of Ajax usage simple tutorial. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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