Ajax -- Getting Started

读了一下MDNAjax文档,做一下记录,不过内容不是很多,更详细的内容请看Reference

The two features provided by Ajax:

  1. Make requests to the server without reloading the page
  2. Receive and work with data from the server

Step 1 – How to make an HTTP request

  1. Create an XMLHttpRequest object

    don’t take account of IE browser.
    var xml = new XMLHttpRequest()

  2. Tell XHLHttpRequest object what to do after receiving server response

    1
    2
    3
    4
    5
    xml.onreadystatechange = function() {
    if (xml.readyState === 4 && xml.status === 200) {
    // do something
    }
    }
  3. Make the request

    1
    2
    httpRequest.open('GET', 'http://www.example.org/some.file', true);
    httpRequest.send(null);

Step 2 – Handling the server response

the full list of readyState value is as follow:

  • 0 (uninitialized)
  • 1 (loading)
  • 2 (loaded)
  • 3 (interactive)
  • 4 (complete)

-

  1. check the response code of the http response

    1
    2
    3
    4
    5
    if (xml.status === 200) {
    // perfect
    } else {
    // there was a problem with the request
    }
  2. access the data from the server
    you have two options to access the data:

    1. httpRequest.responseText – returns the server response as a string of text
    2. httpRequest.responseXML – returns the response as an XMLDocument object you can traverse using the JavaScript DOM functions
  3. cancel the asynchronous request
    you can canel the request by running abort() before you receving the data from the server.

Referrence

  1. Getting Started