Another RayJune

AJAX from MDN

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:

  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
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
2
request.open('GET', 'http://www.rayjune.me/resume.pdf', true);
request.send();

parameter:

  1. HTTP request method – GET, POST, HEAD, or another method supported by your server. Keep all-capitals.
  2. The URL you’re sending the request to
  3. 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
2
3
4
5
if (request.readyState === XMLHttpRequest.DONE) {
// Everything is good, the response was received.
} else {
// Not ready yet.
}

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
2
3
4
5
6
7
if (request.status === 200) {
// Perfect!
} else {
// There was a problem with the request.
// For example, the response may have a 404 (Not Found)
// or 500 (Internal Server Error) response code.
}

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 text
  • httpRequest.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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<button id="AJAXButton" type="button">Make a request</button>

<script>
(function () {
var request;

document.getElementById("AJAXButton").addEventListener('click', makeRequest);

function makeRequest() {
request = new XMLHttpRequest();
request.onreadystatechange = alertContents;
request.open('GET', 'test.html');
request.send();
}

function alertContents() {
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status === 200) {
alert(request.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
})();
</script>

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
2
3
4
5
6
7
8
9
10
11
12
13
14
function alertContents() {
try {
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status === 200) {
alert(request.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
catch( e ) {
alert('Caught Exception: ' + e.description);
}
}

Step 4 – Working with data

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<label>Your name: 
<input type="text" id="AJAXTextbox" />
</label>
<span id="AJAXButton" style="cursor: pointer; text-decoration: underline">
Make a request
</span>

<script>
document.getElementById("AJAXButton").onclick = function () {
var userName = document.getElementById("AJAXTextbox").value;

makeRequest('test.php', userName);
};

function makeRequest(url, userName) {
...

request.onreadystatechange = alertContents;
request.open('POST', url);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.send('userName=' + encodeURIComponent(userName));
}
</script>

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
2
3
4
5
6
7
8
9
10
11
function alertContents() {
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status === 200) {
var response = JSON.parse(request.responseText);

alert(response.computedString);
} else {
alert('There was a problem with the request.');
}
}
}

Reference & Thanks

MDN:
https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX

文章标题:AJAX from MDN

文章作者:RayJune

时间地点:上午 9:53,于又玄图书馆

原始链接:https://www.rayjune.me/2018/03/17/AJAX-from-MDN/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。