Asynchronous JavaScript And XML.
Summarized from MDN
Introduce
AJAX stands for Asynchronous JavaScript And XML. In a nutshell, it is the use of the XMLHttpRequest object to communicate with servers.
AJAX’s most appealing characteristic is its “asynchronous” nature, which means it can communicate with the server, exchange data, and update the page without having to refresh the page.
The two major features of AJAX allow you to do the following:
- Make requests to the server without reloading the page
- Receive and work with data from the server
Step 1 – How to make an HTTP request
1 | var request = new XMLHttpRequest(); |
After making a request, you will receive a response back.
By setting the onreadystatechange
property of the object, like this:
1 | request.onreadystatechange = () => { doSomething }; |
Next, you need to actually make the request, by calling the open()
and send()
methods of the HTTP request object, like this:
1 | request.open('GET', 'http://www.rayjune.me/resume.pdf', true); |
parameter:
- HTTP request method – GET, POST, HEAD, or another method supported by your server. Keep all-capitals.
- The URL you’re sending the request to
- Optional, sets whether the request is asynchronous. If true (the default), JavaScript execution will continue and the user can interact with the page while the server response has yet to arrive.
The parameter to the send()
method can be any data you want to send to the server if POST-ing the request.
Form data should be sent in a format that the server can parse, like a query string:
1 | "name=value&anothername="+encodeURIComponent(myVar)+"&so=on" |
or other formats, like multipart/form-data, JSON, XML, and so on.
Note that if you want to POST data, you may have to set the MIME type of the request.
For example, use the following before calling send()
for form data sent as a query string:
1 | request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); |
Step 2 - Handling the server response
When you sent the request, you provided the name of a JavaScript function to handle the response:
1 | request.onreadystatechange = nameOfTheFunction; |
First, the function needs to check the request’s state.
If the state has the value of XMLHttpRequest.DONE
(corresponding to 4), that means that the full server response was received and it’s OK for you to continue processing it.
1 | if (request.readyState === XMLHttpRequest.DONE) { |
The full list of the readyState
values is as follows:
- 0 (UNSENT) or (request not initialized)
- 1 (OPENED) or (server connection established)
- 2 (HEADERS_RECEIVED) or (request received)
- 3 (LOADING) or (processing request)
- 4 (DONE) or (request finished and response is ready)
- 0 (未初始化) or (请求还未初始化)
- 1 (正在加载) or (已建立服务器链接)
- 2 (加载成功) or (请求已接受)
- 3 (交互) or (正在处理请求)
- 4 (完成) or (请求已完成并且响应已准备好)
Next, check the response code of the HTTP response. In the following example, we differentiate between a successful and unsuccessful AJAX call by checking for a 200 OK response code.
1 | if (request.status === 200) { |
Next, we can do whatever we want with the data the server sent. We have two options to access that data:
httpRequest.responseText
: returns the server response as a string of texthttpRequest.responseXML
: returns the server response as an XMLDocument object you can traverse with JavaScript DOM functions
Note that the steps above are valid only if you used an asynchronous request (the third parameter of open() was unspecified or set to true). If you used a synchronous request you don’t need to specify a function, but this is highly discouraged as it makes for an awful user experience.
Step 3 – A Simple Example
Let’s put it all together with a simple HTTP request. Our JavaScript will request an HTML document, test.html, which contains the text “I’m a test.” Then we’ll alert()
the contents of the response.
1 | <button id="AJAXButton" type="button">Make a request</button> |
In the event of a communication error (such as the server going down), an exception will be thrown in the onreadystatechange
method when accessing the response status. To mitigate this problem, you could wrap your if...then
statement in a try...catch
:
1 | function alertContents() { |
Step 4 – Working with data
1 | <label>Your name: |
the server’s response would look like this:
1 | {"userData":"Jane","computedString":"Hi, Jane!"} |
To use this data within alertContents()
, we need to parse it and alert computedString, the property we want:
1 | function alertContents() { |