[Mozilla] Ajax Quick Start

Source: Internet
Author: User
Tags tld mozilla developer network

What is Ajax?

The meaning of Ajax is asynchronous JavaScript and XML. In short, it is 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 appealing thing about Ajax is its "asynchronous" nature, which means that Ajax can communicate with the server without having to refresh the page. Allows you to update some page content based on user events.

Two features to consider:

    • Sends a request to the server without reloading the page.
    • Receive data from the server side and process it.
First step: How to send an HTTP request

You need to use JavaScript to send an HTTP request to the server by using the XMLHttpRequest implementation. The introduction of an ActiveX object named XMLHTTP in Internet Explorer (IE) implements the same functionality as XMLHttpRequest, while Mozilla, Safari, and other browsers use XMLHttpRequest.

If you want to be compatible with each browser, you can do this:

var httpRequest;if...    elseif6 and older    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");}

Note: For demonstration purposes, creating a XMLHTTP instance above is a simplified code. See the third step of this article for a more realistic example.

Next, when you receive a server-side response, you need to tell the HTTP request object to use JavaScript functions to handle the response. Sets the onReadyStateChange property of the XMLHttpRequest object to the name of the function, which is called when the state of the request changes.

httpRequest.onreadystatechange = nameOfTheFunction;

Note: The function name does not pass the parentheses and arguments of the arguments, which means that only a reference to a function is assigned, not the function that is actually called. Of course, you can also dynamically define an anonymous function so that the response can be processed in real time.

function(){    // process the server response};

After processing the server-side response, we can invoke the open () and send () methods of the XMLHttpRequest object to send the request to the server side.

httpRequest.open(‘GET‘http://www.example.org/some.file‘, true);httpRequest.send(null);
    • The first parameter of the Open () method: The HTTP request Method-GET, POST, head, and any server-side supported methods. Keep uppercase according to the HTTP standard, or some browsers (such as Firefox) may not be able to process requests. For more information on the HTTP request method, you can view the specifications
    • The second parameter of the Open () method: the requested URL. For security reasons, you cannot invoke the page content of a third-party domain. When calling the open () method, be sure to use pages within the same domain name, otherwise you will get "Permission denied" error. A common mistake is to use DOMAIN.TLD to access a Web site, but use WWW.DOMAIN.TLD 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. If True (the default value), the representation is an asynchronous request.

The parameters of the Send () method indicate that the requested data content is sent to the server side when the request is post. If the form data format is sent, the server side can parse the string as well.

"name=value&anothername="+encodeURIComponent(myVar)+"&so=on"

The data format sent to the server can also be in JSON, SOAP, and other formats.

Note: If you send data using post, you need to set the MIME type of the request before calling the Send () method. :

httpRequest.setRequestHeader(‘Content-Type‘application/x-www-form-urlencoded‘);
Step two: Handle server-side response

When a request is sent, a function has been defined to handle the response.

httpRequest.onreadystatechange = nameOfTheFunction;

What can this function do? First, the function needs to check the status of the request. If the status value is 4, this means that the completed server-side response is received and can continue processing.

if4) {    //else {    //not ready}

The list of values for readystate is as follows:

    • 0-not initialized
    • 1-Loading
    • 2-Loading complete
    • 3-In interaction
    • 4-Done

Next you need to check the status code of the HTTP server-side response, which lists all the status codes. In the following example, whether the AJAX call is successful is determined by whether the status code is OK.

if200) {    // 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 status of the request and the status code of the response, it is possible to receive and process the data sent by the server side. There are two options for accessing this data:

    • Httprequest.responsetext-Returns the server-side response as a text string
    • Httprequest.responsexml-Returns the response as a XmlDocument object that can be traversed using JavaScript dom functions.

Note that the above steps are valid only if the asynchronous request (the third argument of the open () method is set to true). If you are using a synchronous request, you do not need to specify a function. After calling the Send () method, you can access the data returned by the server side, because the script stops and waits for the server-side response.

Step Three: A simple example

Here's a simple HTTP request. JavaScript will request a containing "I ' m a test." The text of the "test.html" HTML document, and then use the alert () method to print the contents of the test.html file.

<span id="Ajaxbutton" style="Cursor:pointer; Text-decoration:underline ">Make a request</span><script type="Text/javascript">( function() {  varHttpRequest; document.getElementById ("Ajaxbutton"). onclick = function() {MakeRequest (' test.html '); }; function makerequest(URL) {    if(Window. XMLHttpRequest) {//Mozilla, Safari, ...HttpRequest =NewXMLHttpRequest (); }Else if(Window. ActiveXObject) {//IE      Try{HttpRequest =NewActiveXObject ("Msxml2.xmlhttp"); }Catch(e) {Try{HttpRequest =NewActiveXObject ("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 = = = $) {alert (httprequest.responsetext); }Else{Alert (' There is a problem with the request. '); }    }  }})();</script>

In this example:

    • In the browser, the user clicks the "Make a Request" link;
    • The event handler calls the MakeRequest () method, requesting a "test.html" HTML file in the same directory by passing parameters to the function;
    • After the request, (onreadystatechange) executes the alertcontents () method;
    • The Alertcontents () method is used to check if a response is received correctly, using the alert () method to print what the "test.html" file contains.

Note: If you send a request and return an XML code instead of a static XML file, you must set up some response headers in Internet Explorer. If the response header "Content-type:application/xml" is not set, ie throws an "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 resubmit the request. You can add different get request parameters like timestamps or a random number (refer to bypassing the cache).

Note: If the HttpRequest variable is global, the MakeRequest () method may be overridden because of a conflict. You can avoid the conflicts of Ajax functions by defining the HttpRequest variable in a closure.

Note: If there is a communication error (such as a server-side shutdown), an exception will be thrown in the onReadyStateChange method when attempting to access the Status field. Make sure that the IF statement is declared in try: The 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{    alert(‘Caught Exception: ‘ + e.description);  }}
Fourth step: Using XML to respond

In the previous example, when a response is received, the ResponseText property of the XMLHttpRequest object is used to access the content contained in the "test.html" file. Now try the Responsexml property.

First, create a valid XML document called "Test.xml" for the request, with the following code:

<?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, you need to replace alert (Httprequest.responsetext) with the following code:

var= httpRequest.responseXML;var= 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.

Fifth step: Working with Data

Finally, send some data to the server side and receive the response. This JavaScript script requests a dynamic page "test.php" that will return a "computedstring"-"Hello, [user data]!") based on the data sent, and print using the alert () method.

First, add a text box to the HTML page that allows the user to enter their name 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 a line of event handlers to get the user's data from the text box and pass that data to the MakeRequest () method with the URL:

  document.getElementById("ajaxButton"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 side. Modify the request mode from Get to post, and the user data is passed as a parameter to the Httprequest.send () method:

  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 use the alert () method to print the data returned by the server side as a third step. Assuming that the server side returns computedstring and user data, if the user enters the content of the "Jane" server-side response in the text box, it will look like this:

{"UserData": "Jane", "computedstring": "Hi, jane!"}

Using this data in the Alertcontents () method, you can not only print the contents of the ResponseText using the alert () method, but also parse and print the Computedstring property contents:

function alertContents() {  if4) {    if200) {      varJSON.parse(httpRequest.responseText);      alert(response.computedString);    else {      alert(‘There was a problem with the request.‘);    }  }}

indicate:
This article translates to the Mozilla Developer Network
Translated by: Fellow
Original address: https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started

[Mozilla] Ajax Quick Start

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.