[Mozilla] AJAX Quick Start, mozillaajax
What Is AJAX?
AJAX means Asynchronous JavaScript and XML. In short, it is a scripting language that uses the XMLHttpRequest object to communicate with the server. It can send and receive information in various formats, including JSON, XML, HTML, and text files. AJAX is most attractive because of its "Asynchronous" feature, which means that AJAX can communicate with the server without refreshing the page. Allows you to update part of the page content based on user events.
Two features can be considered:
- Send a request to the server without reloading the page.
- Receives and processes data from the server.
Step 1: How to send an HTTP request
You must use XMLHttpRequest to send an HTTP request to the server using JavaScript. Internet Explorer (IE) introduces an ActiveX object named XMLHTTP to implement the same functions as XMLHttpRequest. Mozilla, Safari, and other browsers use XMLHttpRequest.
To be compatible with various 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");}
Note:For demonstration purposes, the above Code is simplified to create an XMLHTTP instance. For more real examples, see Step 3 in this article.
Next, when receiving the server response, you need to tell the HTTP request object to use JavaScript Functions to process the response. Set the onreadystatechange attribute of the XMLHttpRequest object to the name of the function. When the Request status changes, the function is called.
httpRequest.onreadystatechange = nameOfTheFunction;
Note:The function name does not pass the brackets and parameters of the parameter. This indicates that only a function reference is assigned, rather than actually calling the function. Of course, you can also dynamically define an anonymous function to process the response in real time.
httpRequest.onreadystatechange = function(){ // process the server response};
After processing the server response, we can call the open () and send () Methods of the XMLHttpRequest object to send requests to the server.
httpRequest.open('GET', 'http://www.example.org/some.file', true);httpRequest.send(null);
- The first parameter of the open () method is the HTTP Request Method-GET, POST, HEAD, and methods supported by any server. Keep the HTTP standard in uppercase; otherwise, Some browsers (such as Firefox) may not be able to process requests. For more information about HTTP request methods, see W3C specifications.
- The second parameter of the open () method: the request URL. For security reasons, you cannot call the page content of the third-party domain. When you call the open () method, be sure to use pages within the same domain name. Otherwise, the error message "permission denied" is displayed. A common error is that domain. tld is used to access a website, but www. domain. tld is used to request a page. If you really need to send a request to another domain, you can view the HTTP access control
- The third parameter of the open () method: (optional) whether it is an asynchronous request. True (default) indicates an asynchronous request.
The parameter of the send () method indicates the data content of the request sent to the server when the request is POST. If the form data format is sent, the server can parse the data in the same way as the string.
"name=value&anothername="+encodeURIComponent(myVar)+"&so=on"
The data format sent to the server can also be JSON or SOAP.
Note:If you use POST to send data, you must set the MIME type of the request before calling the send () method. :
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
Step 2: process the Server Response
When a request is sent, a function has been defined to process the response.
httpRequest.onreadystatechange = nameOfTheFunction;
What can this function do? First, the function needs to check the Request status. If the status value is 4, it indicates that the server-side response is received and can be processed.
if (httpRequest.readyState === 4) { // everything is good, the response is received} else { // still not ready}
The Value List of readyState is as follows:
- 0-not initialized
- 1-loading
- 2-Load completed
- 3-interaction in progress
- 4-complete
Next, check the status code of the HTTP server response. The W3C website lists all the status codes. In the following example, check whether the AJAX call is successful by checking whether the status code is 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}
After checking the Request status and response status code, you can receive and process data sent by the server. There are two options to access the data:
- HttpRequest. responseText-return the server-side response as a text string
- HttpRequest. responseXML-returns a response as an XMLDocument object, which can be traversed using the JavaScript DOM function.
Note:The preceding steps are valid only when the third parameter of the asynchronous request (open () method is set to true. If synchronous requests are used, you do not need to specify a function. After calling the send () method, you can access the data returned by the server, 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 an example test.html#html file containing "I'm a test.htm", and then print the content of the test.html file using alert().
<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>
In this example:
- In the browser, click the "Make a request" link;
- The event handler calls the makerequest(upload folder, and requests an HTML file test.html in the same directory as the uploaded file;
- After the request, (onreadystatechange) executes the alertContents () method;
- Alertcontents(your contents is used to check the content contained in the alert( "“test.html "file if the receiver receives the response.
Note:If an XML code is returned after a request is sent, rather than a static XML file, some response headers must be set in Internet Explorer. If the response header "Content-Type: application/xml" is not set, IE will throw a "Object Expected" JavaScript error when attempting to access the XML element.
Note:If the header "Cache-Control: no-cache" is not set, the browser caches the response and does not submit the request again. You can add different GET request parameters such as timestamp or a random number (refer to bypassing the cache ).
Note:If the httpRequest variable is global, the makeRequest () method may be overwritten because of the conflict. Defining the httpRequest variable in a closure can avoid AJAX function conflicts.
Note:If a communication error occurs (for example, the server is disabled), an exception is thrown in the onreadystatechange method when you try to access the Status field. Make sure that the if statement is 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); }}
Step 4: use XML for response
In the previous example, use the content contained in the responsetext000000000000test.html file of the xmlhttprequestobject after receiving the response. Now try the responseXML attribute.
First, create a valid xml document named "test. XML" for the request. The Code is as follows:
<?xml version="1.0" ?><root> I'm a test.</root>
In the script, you only need to modify the request line:
onclick="makeRequest('test.xml')">
Then in the alertContents () method, replace alert (httpRequest. responseText) with the following code:
var xmldoc = httpRequest.responseXML;var root_node = xmldoc.getElementsByTagName('root').item(0);alert(root_node.firstChild.data);
This Code requires the XMLDocument object given by responseXML, and then uses the DOM method to access the data in the XML document.
Step 5: Process Data
Finally, send some data to the server and receive the response. This JavaScript script requests a dynamic page "test. php", which returns a "computedString"-"Hello, [user data]!" based on the sent data. Use the alert () method for printing.
First, add a text box to the HTML page. You can enter their names in the text box:
<label>Your name: <input type="text" id="ajaxTextbox" /></label><span id="ajaxButton" style="cursor: pointer; text-decoration: underline"> Make a request</span>
You also need to add an event processor to get user data from the text box and pass the data along with the URL to the makeRequest () method:
document.getElementById("ajaxButton").onclick = function() { var userName = document.getElementById("ajaxTextbox").value; makeRequest('test.php',userName); };
Modify the makeRequest () method to receive user data and send it to the server. Modify the request method from GET to POST. User data is passed to the httpRequest. send () method as a parameter:
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)); }
The alertContents () method can print the data returned by the server using the alert () method in step 3. Assume that the server returns computedString and user data. If the user enters "Jane" in the text box, the response content on the server will look like this:
{"UserData": "Jane", "computedString": "Hi, Jane !"}
When using the data in the alertContents () method, you can not only use the alert () method to print the content of responseText, but also parse and print the content of the computedString attribute:
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.'); } }}
Note:
This article is translated from Mozilla Developer Network
Translator: Jin Yunlong
Address: https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started