Home > Article > Web Front-end > Understanding of XHR objects in ajax series
Previous words
In 1999, Microsoft released IE5, which introduced a new feature for the first time: allowing javascript scripts to initiate HTTP requests to the server. This feature did not attract attention at the time. It was not until the release of Gmail in 2004 and Google Map in 2005 that it attracted widespread attention. In February 2005, the term ajax was officially proposed for the first time, referring to a set of development practices around this function. Since then, ajax has become synonymous with script-initiated HTTP communication, and W3C also released its international standard in 2006. This article is the first article in the ajax series - XHR object
Ajax is the abbreviation of asynchronous javascript and XML. The Chinese translation is asynchronous javascript and XML. This technology can request the server Additional data without having to unload the page will result in a better user experience. Although the name contains XML, ajax communication has nothing to do with data format
Ajax includes the following steps: 1. Create an AJAX object; 2. Issue an HTTP request; 3. Receive data returned by the server; 4. Update the web page Data
To sum up, in one sentence, ajax sends an HTTP request through the native XMLHttpRequest
object, and then processes the data returned by the server
The core of ajax technology is the XMLHttpRequest object (XHR for short), which is a feature first introduced by Microsoft. Other browser providers later provided the same implementation. XHR provides a fluent interface for sending requests to the server and parsing server responses. It can obtain more information from the server asynchronously, which means that after the user clicks, he can obtain new data without refreshing the page
IE5 It was the first browser to introduce XHR objects. In IE5, the XHR object is implemented through an ActiveX object in the MSXML library, while IE7+ and other standard browsers support native XHR objects
Creating an XHR object is also called instantiating an XHR object. Because XMLHTTPRequest() is a constructor. The following is a compatible way of writing an XHR object
var xhr; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject('Microsoft.XMLHTTP'); }
[Note] If you want to create N different requests, you must use N different XHR objects. It is of course possible to reuse an existing XHR object, but this will terminate any requests previously pending through that object
open()
When using an XHR object, the first method to be called is open(), as shown below. This method accepts 3 parameters
xhr.open("get","example.php", false);
1. The first parameter of the open() method is used to specify the method of sending the request. This string is not case-sensitive, but uppercase letters are usually used. "GET" and "POST" are widely supported
"GET" is used for regular requests. It is suitable when the URL completely specifies the requested resource, when the request has no side effects on the server, and when the server's response is available. In the case of caching
The "POST" method is often used in HTML forms. It includes additional data in the request body and this data is often stored in a database on the server. Repeated POST requests for the same URL may get different responses from the server, and requests using this method should not be cached
In addition to "GET" and "POST", the parameters can also be "HEAD" and "OPTIONS" ","PUT". Due to security risks, the use of "CONNECT", "TRACE" and "TRACK" is prohibited
[Note] The detailed introduction to the 8 commonly used methods of the HTTP protocol is here
2 The second parameter of the open() method is the URL, which is relative to the current page where the code is executed, and can only send requests to URLs in the same domain that use the same port and protocol. If there is any difference between the URL and the page that initiates the request, a security error will occur
3. The third parameter of the open() method is a Boolean value indicating whether to send the request asynchronously. If not filled in, the default is true. Indicates asynchronous sending
4. If requesting a password-protected URL, pass the username and password used for authentication as the 4th and 5th parameters to the open() method
send()
The send() method receives a parameter, which is the data to be sent as the request body. After calling the send() method, the request is dispatched to the server
If it is the GET method, the send() method has no parameters, or the parameter is null; if it is the POST method, the parameters of the send() method are the ones to be sent. Data
xhr.open("get", "example.txt", false); xhr.send(null);
A complete HTTP response consists of a status code, a collection of response headers and a response body. After receiving the response, these can be used through the properties and methods of the XHR object. There are mainly the following 4 properties
responseText: 作为响应主体被返回的文本(文本形式) responseXML: 如果响应的内容类型是'text/xml'或'application/xml',这个属性中将保存着响应数据的XML DOM文档(document形式) status: HTTP状态码(数字形式) statusText: HTTP状态说明(文本形式)
在接收到响应后,第一步是检查status属性,以确定响应已经成功返回。一般来说,可以将HTTP状态码为200作为成功的标志。此时,responseText属性的内容已经就绪,而且在内容类型正确的情况下,responseXML也可以访问了。此外,状态码为304表示请求的资源并没有被修改,可以直接使用浏览器中缓存的版本;当然,也意味着响应是有效的
无论内容类型是什么,响应主体的内容都会保存到responseText属性中,而对于非XML数据而言,responseXML属性的值将为null
if((xhr.status >=200 && xhr.status
如果接受的是同步响应,则需要将open()方法的第三个参数设置为false,那么send()方法将阻塞直到请求完成。一旦send()返回,仅需要检查XHR对象的status和responseText属性即可
同步请求是吸引人的,但应该避免使用它们。客户端javascript是单线程的,当send()方法阻塞时,它通常会导致整个浏览器UI冻结。如果连接的服务器响应慢,那么用户的浏览器将冻结
<button>获取信息</button> <div></div> <script> btn.onclick = function(){ //创建xhr对象 var xhr; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject('Microsoft.XMLHTTP'); } //发送请求 xhr.open('get','/uploads/rs/26/ddzmgynp/message.xml',false); xhr.send(); //同步接受响应 if(xhr.readyState == 4){ if(xhr.status == 200){ //实际操作 result.innerHTML += xhr.responseText; } } } </script>
//message.xml <p>hello world</p>
如果需要接收的是异步响应,这就需要检测XHR对象的readyState属性,该属性表示请求/响应过程的当前活动阶段。这个属性可取的值如下:
0(UNSENT):未初始化。尚未调用open()方法 1(OPENED):启动。已经调用open()方法,但尚未调用send()方法 2(HEADERS_RECEIVED):发送。己经调用send()方法,且接收到头信息 3(LOADING):接收。已经接收到部分响应主体信息 4(DONE):完成。已经接收到全部响应数据,而且已经可以在客户端使用了
理论上,只要readyState属性值由一个值变成另一个值,都会触发一次readystatechange事件。可以利用这个事件来检测每次状态变化后readyState的值。通常,我们对readyState值为4的阶段感兴趣,因为这时所有数据都已就绪
[注意]必须在调用open()之前指定onreadystatechange 事件处理程序才能确保跨浏览器兼容性,否则将无法接收readyState属性为0和1的情况
xhr.onreadystatechange = function(){ if(xhr.readyState === 4){ if(xhr.status == 200){ alert(xhr.responseText); } } }
<button>获取信息</button> <div></div> <script> btn.onclick = function(){ //创建xhr对象 var xhr; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject('Microsoft.XMLHTTP'); } //异步接受响应 xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 200){ //实际操作 result.innerHTML += xhr.responseText; } } } //发送请求 xhr.open('get','message.xml',true); xhr.send(); } </script>
//message.xml <p>hello world</p>
XHR对象的timeout属性等于一个整数,表示多少毫秒后,如果请求仍然没有得到结果,就会自动终止。该属性默认等于0,表示没有时间限制
如果请求超时,将触发ontimeout事件
[注意]IE8-浏览器不支持该属性
xhr.open('post','test.php',true); xhr.ontimeout = function(){ console.log('The request timed out.'); } xhr.timeout = 1000; xhr.send();
使用AJAX接收数据时,由于网络和数据大小的原因,并不是立刻就可以在页面中显示出来。所以,更好的做法是,在接受数据的过程中,显示一个类似loading的小图片,并且禁用按钮;当数据完全接收后,再隐藏该图片,并启用按钮
<button>获取信息</button> <img alt="Understanding of XHR objects in ajax series" > <div></div> <script> var add = (function(){ var counter = 0; return function(){ return ++counter; } })(); btn.onclick = function(){ img.style.display = 'inline-block'; btn.setAttribute('disabled',''); //创建xhr对象 var xhr; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject('Microsoft.XMLHTTP'); } //异步接受响应 xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 200){ img.style.display = 'none'; btn.removeAttribute('disabled'); var data = JSON.parse(xhr.responseText); var sum = add() - 1; if(sum < data.length){ result.innerHTML += data[sum]; } } } } //发送请求 xhr.open('get','data.php',true); xhr.send(); } </script>
<?php echo json_encode([1,2,3,4,5]); ?>
Finally
Through the demonstration of examples, we found that the content of the ajax front-end itself is not difficult. However, since ajax involves some back-end and network knowledge, it is not easy to learn. Future blog posts will gradually introduce the key contents of ajax in depth
The above is the detailed content of Understanding of XHR objects in ajax series. For more information, please follow other related articles on the PHP Chinese website!