Deep understanding of the first article of the AJAX series XHR object _ajax related

Source: Internet
Author: User
Tags xml dom document

Front.

Ajax is shorthand for asynchronous JavaScript and XML, the Chinese translation is asynchronous JavaScript and XML, this technology can request additional data to the server without unloading the page, will bring a better user experience. Although the name contains XML, AJAX traffic is independent of the data format. The Ajax content is described in detail below

Create

The core of Ajax technology is the XMLHttpRequest object (referred to as XHR), a feature introduced by Microsoft in the first place, which later provided the same implementation by other browser providers. XHR provides a fluent interface for sending requests to the server and analyzing the server response, making it possible to get more information from the server asynchronously, meaning that once clicked, users can get new data without refreshing the page

IE5 is 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

Creates a Xhr object, also called instantiating a Xhr object, because XMLHttpRequest () is a constructor. The following is a compatible notation for creating XHR objects

var xhr;
if (window. XMLHttpRequest) {
  xhr = new XMLHttpRequest ();
} else{
  xhr = new ActiveXObject (' microsoft.xmlhttp ');
}

Send Request

Open ()

When using the Xhr object, the first method to invoke is open (), which accepts 3 parameters: the type of request to send ("get", "post", and so on), the requested URL, and a Boolean value that represents whether the request is sent asynchronously

Xhr.open ("Get", "example.php", false);

Attention The URL is the current page relative to the execution code and can only send requests to URLs that use the same ports and protocols in the same domain. A security error can be raised if the URL differs from the page on which the request was initiated

Send ()

The Send () method receives a parameter, which is the data to be sent as the body of the request. After the Send () method is called, the request is dispatched to the server

Xhr.open ("Get", "Example.txt", false);
Xhr.send (NULL);

Receive response

After the response is received, the response data is automatically populated with the properties of the Xhr object, with the following 4 properties

ResponseText: Text returned as a response body

Responsexml: If the content type of the response is ' text/xml ' or ' application/xml ', this property will hold the XML DOM document of the response data

Status: HTTP status of the response

Description of Statustext:http Status

After receiving the response, the first step is to check the Status property to determine that the response has been successfully returned. In general, the HTTP status code can be 200 as a sign of success. At this point, the contents of the ResponseText property are ready and responsexml can be accessed if the content type is correct. In addition, a status code of 304 indicates that the requested resource has not been modified and can be used directly in the cached version of the browser, and, of course, that the response is valid

The content of the response body is saved to the ResponseText property regardless of the content type, and the value of the Responsexml property is null for non-XML data

if ((Xhr.status >=200 && xhr.status <) | | xhr.status = = 304) {
  alert (xhr.responsetext);
} else{
  alert (' request was unsuccessful: ' + xhr.status);
}

Asynchronous

If you need to receive an asynchronous response, you need to detect the ReadyState property of the Xhr object, which represents the current active phase of the request/response process. The values that are desirable for this property are as follows:

0 (Unsent): not initialized. The open () method has not been called

1 (opened): Start. The open () method has been called, but the Send () method has not been invoked

2 (headers_received): send. The Send () method has been called and receive header information

3 (LOADING): Receive. Part of the response body information has been received

4 (Done): complete. All response data has been received and can already be used on the client

Whenever the ReadyState property value is changed from one value to another, a ReadyStateChange event is triggered. You can use this event to detect readystate values after each state change. Normally, we're interested in a stage with a readystate value of 4 because all the data is ready

[Note] You must specify the onReadyStateChange event handler before calling open () to ensure cross-browser compatibility, otherwise you will not be able to receive the ReadyState property 0 and 1

Xhr.onreadystatechange = function () {
  if (xhr.readystate = = 4) {
    if (Xhr.status =) {
      alert ( Xhr.responsetext);}}

Instance

Here is a small example to illustrate the application of XHR objects in Ajax

<button id= "BTN" > Get information </button>
<div id= "result" ></div>
<script>
Btn.onclick = function () {
  ///Create XHR object
  var xhr;
  if (window. XMLHttpRequest) {
    xhr = new XMLHttpRequest ();
  } else{
    xhr = new ActiveXObject (' microsoft.xmlhttp ');
  }
  Asynchronous Accept response
  Xhr.onreadystatechange = function () {
    if (xhr.readystate = 4) {
      if (Xhr.status =) {
        // Actual operation
        result.innerhtml + = Xhr.responsetext
      ;
    }
  } Send Request
  xhr.open (' Get ', ' message.xml ', true);
  Xhr.send ();
}
</script>

Message.xml

<p>hello world</p>

At last

The demo of the example shows that the content of Ajax front-end itself is not difficult. However, because Ajax involves some backend and network knowledge, it is not easy to learn. Future posts will be a step-by-step introduction to Ajax focus

The above is a small series to introduce the in-depth understanding of the Ajax series of the first XHR object, I hope to help you!

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.