This article was first published on a personal website: From getting started with Ajax to getting it right, one article is enough
This article was translated from Mozilla Developer Network
Translator: Don’t want to mature uncle
Original address: developer.mozilla.org/en-US/docs/…
What is Ajax?
Ajax stands for asynchronous JavaScript and XML. In short, it’s a scripting language that uses XMLHttpRequest objects to communicate with the server side. It can send and receive information in a variety of formats, including JSON, XML, HTML, and text files. The most attractive aspect of Ajax is its “asynchronous” nature, which means that Ajax can communicate with the server side without refreshing the page. Allows you to update parts of the page based on user events.
Two features to consider:
- Send requests to the server side without reloading the page.
- Receives data from the server and processes it.
Step 1: How do I send an HTTP request
You need an XMLHttpRequest implementation to send an HTTP request to the server side using JavaScript. In Internet Explorer (IE), an ActiveX object called XMLHTTP implements the same functionality as XMLHttpRequest, which is used by Mozilla, Safari, and other browsers.
To be compatible with all browsers, you can do this:
var httpRequest;
if (window.XMLHttpRequest) {
// Mozilla, Safari, IE7+ ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) {
// IE 6 and older
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
Copy the code
Note: Creating an XMLHTTP instance above is simplified code for demonstration purposes. For a more realistic example, see step 3 of this article.
Next, when you receive the server-side response, you need to tell the HTTP request object to use JavaScript functions to process the response. Set the onReadyStatechange property of the XMLHttpRequest object to the name of the function that will be called when the status of the request changes.
httpRequest.onreadystatechange = nameOfTheFunction;
Copy the code
Note: This function name does not pass parentheses and arguments, which means that you are assigning a reference to a function, not actually calling the function. Of course, you can also define an anonymous function dynamically so that the response can be processed in real time.
httpRequest.onreadystatechange = function () {
// process the server response
};
Copy the code
After processing the server-side response, we can call the open() and send() methods of the XMLHttpRequest object to send the request to the server.
httpRequest.open("GET"."http://www.example.org/some.file".true);
httpRequest.send(null);
Copy the code
open()
Method: HTTP request methods – GET, POST, HEAD, and any server-side supported methods. Keep caps according to the HTTP standard, otherwise some browsers (such as Firefox) may not be able to handle requests. For more information about HTTP request methods, you can check them outThe W3C specificationopen()
The second argument to the method: the REQUESTED URL. For security reasons, page content from a third-party domain cannot be invoked. When callingopen()
Method, ensure that the page in the same domain name is used; otherwise, an error message “Permission denied” is displayed. A common mistake is to use domain-.tld to access a web site and use it insteadwww.domain.tldTo request the page. Check this out if you really need to send a request to another domainHTTP Access controlopen()
The third argument to the method: optional, whether the request is asynchronous. If true (the default), it is an asynchronous request.
The parameters of the send() method represent the data content of the request sent to the server when the request is POST. If you send form data, the server can parse it as if it were a string.
"name=value&anothername=" + encodeURIComponent(myVar) + "&so=on";
Copy the code
The data sent to the server can also be in JSON or SOAP format.
Note: If you use POST to send data, you need to set the MIME type of the request before calling send().
httpRequest.setRequestHeader(
"Content-Type"."application/x-www-form-urlencoded"
);
Copy the code
Step 2: Process the response on the server side
When a request is sent, a function has been defined to handle the response.
httpRequest.onreadystatechange = nameOfTheFunction;
Copy the code
What can this function do? First, the function needs to check the status of the request. A status value of 4 indicates that a completed server-side response has been received and processing can continue.
if (httpRequest.readyState === 4) {
// everything is good, the response is received
} else {
// still not ready
}
Copy the code
The list of readyState values is as follows:
- 0 – Not initialized
- 1 – Loading
- 2 – Loaded
- 3 – Interactive
- 4 – complete
Next you need to examine the status codes for the HTTP server-side response, all of which are listed on the W3C web site. In the following example, whether the Ajax call was successful is determined by a status code of 200 OK.
if (httpRequest.status === 200) {
// perfect!
} else {
// there was a problem with the request,
// for example the response may contain a 404 (Not Found)
// or 500 (Internal Server Error) response code
}
Copy the code
After checking the status of the request and the status code of the response, the data sent by the server can be received and processed. There are two options for accessing this data:
httpRequest.responseText
: Returns the server-side response as a text stringhttpRequest.responseXML
: treats the response as oneXMLDocument
Object that can be traversed using JavaScript DOM functions.
Note that the above steps are valid only for asynchronous requests (the third parameter of the open() method is set to true). There is no need to specify a function if synchronous requests are used. The data returned by the server is accessible after the send() method is called, because the script stops and waits for the response from the server.
Step 3: A simple example
Let’s make a simple HTTP request. JavaScript will request a “test.html” HTML document that contains the text “I’m a test.” Then print the contents of the test.html file using the alert() method.
<span id="ajaxButton" style="cursor: pointer; text-decoration: underline">
Make a request
</span>
<script type="text/javascript">
(function () {
var httpRequest;
document.getElementById("ajaxButton").onclick = function () {
makeRequest("test.html");
};
function makeRequest(url) {
if (window.XMLHttpRequest) {
// Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) {
// IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if(! httpRequest) { alert("Giving up :( Cannot create an XMLHTTP instance");
return false;
}
httpRequest.onreadystatechange = alertContents;
httpRequest.open("GET", url);
httpRequest.send();
}
function alertContents() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {
alert("There was a problem with the request."); }}}}) ();</script>
Copy the code
In this example:
- In the browser, the user clicks the “Make a Request” link.
- Event handler call
makeRequest()
Method to request a “test.html” HTML file in the same directory, using arguments passed to the function; - Upon request, (
onreadystatechange
) performalertContents()
Methods; alertContents()
The method is used to check that if the response is correctly received, thealert()
Method to print the contents of the test. HTML file.
Note:
- If you send a request and return a piece of XML code instead of a static XML file, you must set some response headers in Internet Explorer. If the response header “Content-Type: application/ XML” is not set, IE will throw an “Object Expected” JavaScript error when attempting to access an XML element.
- If the header “cache-control: no-cache” is not set, the browser caches the response and does not resubmit the request. You can add different GET request parameters like a timestamp or a random number (see bypassing the cache).
- if
httpRequest
Variables are global,makeRequest()
Methods may be overwritten because of conflicts. willhttpRequest
Variables defined in a closure can avoid Ajax function collisions.- If a communication error occurs (such as the server being shut down), when attempting to access the status field, the
onreadystatechange
Will throw an exception. Make sure thatif
Statements are declared in the try.. Catch statement.
function alertContents() {
try {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {
alert("There was a problem with the request."); }}}catch (e) {
alert("Caught Exception: "+ e.description); }}Copy the code
Step 4: Use XML to respond
In the previous example, the contents of the “test.html” file are accessed using the responseText property of the XMLHttpRequest object when the response is received. Now try the responseXML property.
First, create a valid XML document named “test.xml” for the request as follows:
<root>
I'm a test.
</root>
Copy the code
In the script, just modify the request line:
onclick="makeRequest('test.xml')"
Copy the code
Then in the alertContents() method, replace alert(Httprequest.responseText) with the following code; This line of code:
var xmldoc = httpRequest.responseXML;
var root_node = xmldoc.getElementsByTagName("root").item(0);
alert(root_node.firstChild.data);
Copy the code
This code takes the XMLDocument object given by responseXML and then uses DOM methods to access the data in the XML document.
Step 5: Process the data
Finally, send some data to the server and receive a response. This time the JavaScript script requests a dynamic page “test.php”, which will return a “computedString” based on the sent data – “Hello, [user data]!” , and prints using the alert() method.
First, add a text box to the HTML page from which the user can enter their name:
<label
>Your name:
<input type="text" id="ajaxTextbox" />
</label>
<span id="ajaxButton" style="cursor: pointer; text-decoration: underline">
Make a request
</span>
Copy the code
You also need to add a line of event handlers to get the user’s data from the text box and pass that data along with the URL to the makeRequest() method:
document.getElementById("ajaxButton").onclick = function () {
var userName = document.getElementById("ajaxTextbox").value;
makeRequest("test.php", userName);
};
Copy the code
Modify the makeRequest() method to receive user data and send it to the server. Change the request mode from GET to POST and pass the user data as an argument to httprequest.send () :
function makeRequest(url, userName) {... httpRequest.onreadystatechange = alertContents; httpRequest.open('POST', url);
httpRequest.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded');
httpRequest.send('userName=' + encodeURIComponent(userName));
}
Copy the code
The alertContents() method prints the data returned by the server using the alert() method as in step 3. Assuming that the server returned a computedString and user data, if the user typed “Jane” into the text box the server response would look something like this:
{"userData":"Jane"."computedString":"Hi, Jane!"}
Copy the code
Using this data in the alertContents() method, we can not only print the contents of the responseText using the alert() method, but also parse and print the contents of the computedString property:
function alertContents() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
var response = JSON.parse(httpRequest.responseText);
alert(response.computedString);
} else {
alert("There was a problem with the request."); }}}Copy the code