Ajax native XHR objects

Source: Internet
Author: User
Tags unique id

The front end has been learning for some time, I usually use jquery encapsulated Ajax functions ($.ajax, $.get, $.post) in the project, but it is very simple and convenient to use, but in order to get a clearer understanding of Ajax, we need to learn native XHR objects. first, make clear what is Ajax,ajax: "Asynchronous JavaScript and XML," which translates to asynchronous JavaScript and XML. Ajax is a technique for creating fast, dynamic Web pages that can be asynchronously updated by Ajax by making a small amount of data exchange in the background with the server. This means that it is possible to update a part of a webpage without reloading the entire page. Create Ajax: to create Ajax, the protagonist is the XMLHttpRequest (hereinafter referred to as XHR) object. First step : Create a Xhr object
var New XMLHttpRequest ();

  Step two : Send a request to the servermethod: Open (Method,url,async) and send (string)The open () method passes in three parameters
    • Method: Type of request (Get/post)
    • URL: The location of the file on the server
    • Async: Boolean value, True for Async, False for synchronization (optional, true by default)
The Send () method sends the request to the server with an optional parameter string, which is used only for post-type requests.  Here is a discussion of the async parameter, where the async parameter of the open () method must be set to True if the XMLHttpRequest object is to be used for Ajax. What happens if the parameter is set to False? The consequence of the synchronization request is that JavaScript waits until the server responds in readiness to continue. The application hangs or stops if it is a larger request or if the server is in a busy state. The simple point is that the page will remain stuck until the response content comes back.  when sending a GET request, it is possible to get cached information (IE), which causes us to send an asynchronous request that does not correctly return the latest data we want. method One: Add a unique ID to the URL: (random number)
1 xhr.open ("GET", "demo.asp?t=" + math.random (),true); 2 xhr.send ();
This way you can avoid getting old messages in the cache, but each request will still be cached by the browser, consuming the browser resources. Method Two: Add an HTTP header to the request using the setRequestHeader (Header,value) method. (about setRequestHeader in the following discussion)
1 xhr.open ("GET", "demo.asp",true); 2 xhr.setrequestheader ("if-modified-since", "0");  // set the browser not to use the cache 3 xhr.send ();
The URL in get can be used to stitch strings to reach the parameters, while transmitting data is usually post. If we send data to the server using the Post method, the HTTP header should be set.
1 xhr.open ("POST", "postdemo.asp",true); 2 xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded");  // Otherwise, the data cannot be received properly . 3 xhr.send ("Name=amie");  // Send to write the data to be sent
Step three: The server responds to the ResponseText and Responsexml properties of the XMLHttpRequest object, respectively, to the response data in the form of a string and to the response data in XML, which can be output in the console Console.log ( Xhr.responsetext); There are also three properties on the response state that are often used:
    • ReadyState: The state of being xmlhttprequest. XHR objects go through 5 different states
      • 0: The request is uninitialized (new after completion);
      • 1: The server connection is established (the object has been created and initialized, the Send method has not been called);
      • 2: The request has been received;
      • 3: in request processing;
      • 4: The request is complete and the response is ready;
    • Status: (HTTP status code is a lot, please know for yourself, for example, common)
      • 200: Request succeeded
      • 404: Page Not Found
    • onReadyStateChange: Stores the function (or the function name), which is called whenever the ReadyState property changes.
So the above line of code can be changed to:
1 function () {2     if (Xhr.readystate = = 4 && xhr.status = =) {3    console.log (xhr.responsetext); 4 };

about setRequestHeaderIn the HTTP protocol, when a client requests a Web page from the server, it needs to send a header file for the HTTP protocol, and XMLHTTP is the file data on the Web site through the HTTP protocol, so it also sends an HTTP header to the server. A header file is sent by default when sending a request, and if we need to modify or add parameters, we need to use the setRequestHeader method. Ps:1. The response header contains a lot of information, and interested small partners can go to know. (HTTP involves a lot of computer network knowledge). 2. Check the HTTP request header to the network in the developer tool.

(written at the end: front-end newcomer One ~ Welcome everyone to point out the mistake, thank you for reading ~)

Ajax native XHR objects

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.