Javascript Basics---Ajax introduction must be read _ basics

Source: Internet
Author: User
Tags event listener

Ajax is a key tool for modern web application development. It allows you to send and receive data asynchronously to the server, and then parse it with Javascript. Ajax is the abbreviation for asynchronous JavaScript and XML (asynchronous JavaScript and XML).

The name of the Ajax core specification inherits from the Javascript object used to create and initiate the request: XMLHttpRequest. This specification has two levels. All major browsers implement the first level, which represents the basic level of functionality. The second level extends the initial specification, incorporating additional events and features to make it easier to collaborate with form elements and support some relevant specifications.

1. Ajax Start

The key to Ajax is XMLHttpRequest objects, and the way to understand this object is to look at an example. The following code shows a simple use of the XMLHttpRequest object:

<! DOCTYPE html>  

Three additional documents are simple:

<! DOCTYPE html>
 
 

The effect is shown in the following illustration:

As the user clicks on each fruit button, the browser executes and retrieves the requested document asynchronously, and the main document is not reloaded. This is typical of Ajax behavior.

2. Using Ajax events

After creating and exploring a simple example, you can begin to learn more about the features supported by the XMLHttpRequest object and how to use them in your request. The starting point is the additional events defined in the second level specification:

Most of these events are triggered at a specific point in time at the request. ReadyStateChange and progress are the exceptions to these events, which can be triggered multiple times to provide progress updates.

When these events are dispatched, the browser uses the regular event object for the ReadyStateChange event and the Progressevent object for other events. The Progressevent object defines all the members of the Event object and adds these members as described in the following illustration:

The following code shows how to use these events:

<!
  DOCTYPE html>  

This is a variant of the previous example, registering a handler function for some events, and creating a record for each event that is processed in a TABLE element. You can see how the Firefox browser triggers these events from the following illustration.

3. Handling Errors

Two types of errors must be heeded when using Ajax. The difference between them stems from different perspectives.

The first type of error is a problem seen from the point of view of the XMLHttpRequest object: Some factors prevent the request from being sent to the server. For example, DNS cannot resolve host names, connection requests are denied, or URLs are not valid.

The second type of problem is the problem seen from the perspective of the application, not the XMLHttpRequest object. They occur when the request is successfully sent to the server, the server receives the request, processes it, and generates a response, but the response does not point to what you expect. For example, this type of problem can occur if the requested URL does not exist.

There are three ways to handle these errors, as shown in the following code:

3.1 Processing Settings Error

The first type of problem that needs to be addressed is to pass the wrong data to the Xmlhttpresquest object, such as an incorrectly formatted URL. They are extremely easy to occur when generating URLs based on user input. To simulate this type of problem, the above document contains a button that adds a bad URL (the wrong URL) to the label. Pressing this button invokes the Open method in the following form:

Httprequest.open ("Get", "http://")

This is an error that prevents the request from executing, while the XMLHttpRequest object throws an error when such an event occurs. This means that you need to surround the code that sets the request with a Try...catch statement, like this:

try{...
      Httprequest.open ("Get", "http://")
      ...
      Httprequest.send ();
    } catch (Error) {
      displayerrormsg ("Try/catch", Error.message)
    }

A catch clause gives you the opportunity to recover from the error. You can choose to prompt the user for a value, or you can fall back to the default URL, or simply discard the request. In this example, only the DISPLAYERRORMSG function is invoked to display the error message.

3.2 Processing Request Error

The second type of error occurs when the request has been generated, but other errors occur. To simulate this type of problem, a button labeled Bad host (the wrong master) was added to the example. When this button is pressed, the open method is called to access an unavailable URL:

Httprequest.open ("Get", http://www.ycdoitt.com/nopage.html)

There are two problems with this URL. The first problem is that the host name cannot be resolved by DNS, so the browser cannot generate a server connection. The problem is that the XMLHttpRequest object becomes apparent when it starts generating the request, so it emits the wrong signal in two ways. If you register an error event listener, the browser sends an event object to your listener function. The following functions are used in the example:

function HandleError (e) {
    displayerrormsg ("Error event", Httprequest.status + Httprequest.statustext);
  }

When this type of error occurs, the extent to which information can be obtained from the XMLHttpRequest object depends on the browser, and unfortunately in most cases, the status and blank statustext values of 0 are obtained.

The second problem is that URLs and build requests have different sources, which are not allowed by default. You can usually send AJAX requests only to the same URL that is loaded into the script. When the browser reports this problem, it may throw an error or trigger an error event, and different browsers will handle the same way. Different browsers also check the source at different points in time, which means that browsers do not always see the browser highlighting the same problem. You can use the cross-station resource specification (Cors,cross-origin Resource sharing) to circumvent the homology restrictions.

3.3 Handling Application Errors

The last type of error occurs when the request completes successfully (from the point of view of the XMLHttpRequest object), but does not return the data you want. To create such a problem, add a button in the example above stating that the label is cucumber. Pressing this button generates a request URL similar to the apples, cherries, and bananas buttons, but the cucumber.html document does not exist on the server.

The process itself has no errors (because the request is complete) and needs to determine what happened based on the status property. When you request a document that exists, you get a status code of 404, which means that the server cannot find the requested document. You can see how the example handles a status code other than 200 (meaning OK):

if (Httprequest.status =) {
        target.innerhtml = Httprequest.responsetext;
      } else{
        document.getElementById ("Statusmsg"). InnerHTML
            = "Status:" + httprequest.status + "" + Httprequest.statustext;
      }

In this example, the values of status and StatusText are simply shown. In real applications, you need to recover in a useful and meaningful way (such as displaying alternate content or alerting users to a problem, specifically, which is more appropriate for your application).

4. Get and set headers

Using the XMLHttpRequest object, you can set the request headers (headers) sent to the server and read the headers in the server response.

4.1 Overwrite the requested HTTP method

Typically, you do not need to add or modify headers in an AJAX request. The browser knows what needs to be sent, and the server knows how to respond. However, there are several exceptions. The first type is the X-http-method-override header.

HTTP standards are often used to request and transmit HTML documents on the Internet, and it defines many methods. Most people know about get and post because they are most widely used. However, there are other methods, including put and delete, that are used to give meaning to the URL requested by the server, and this usage is trending upward. For example, if you want to view a user record, you can generate a request that:

Httprequest.open ("Get", "Http://myserver/records/freeman/adam");

Only the HTTP method and the URL of the request are shown here. For this request to work smoothly, the server side must be able to understand the request by the application and turn it into a piece of appropriate data to send back to the server. If you want to delete data, you can write this:

Httprequest.open ("DELETE", "Http://myserver/records/freeman/adam");

The key here is to use the HTTP method to express what you want the server to do, rather than encode it into the URL in some way.

The problem with using HTTP methods in this way is that many mainstream web technologies only support get and post, and many firewalls allow only get and post requests to pass. There is a common practice to circumvent this limitation by using the X-http-method-override header to specify the HTTP method you want to use, but the form is listed when a POST request is sent. The code demonstrates the following:

<! DOCTYPE html>  

In this example, a setRequestHeader method on the XMLHttpRequest object is used to indicate that the request is to be processed in the form of an HTTP delete method. Please note that I set this header after calling the Open method. If you try to use the setRequestHeader method before the open method, the XMLHttpRequest object throws an error.

PS: Overwriting HTTP requires a server-side Web application framework to understand x-http-method-override this convention, and your server-side application is set up to be able to find and understand those less used HTTP methods.

4.2 Disabling content Caching

The second useful header that can be added to an AJAX request is Cache-control, which is especially useful when writing and debugging scripts. Some browsers cache content obtained through AJAX requests and do not request it again during a browsing session. For the previous example, it means that the changes on the apples.html, cherries.html, and bananas.html are not immediately reflected in the browser. The following code shows how you can set headers to avoid this:

HttpRequest = new XMLHttpRequest ();
    Httprequest.onreadystatechange = Handleresponse;
    Httprequest.open ("Get", e.target.innerhtml+ ". html");
    Httprequest.setrequestheader ("Cache-control", "No-cache");
    Httprequest.send ();

The header is set in the same way as the previous example, but the header used this time is cache-control, and the desired value is no-cache. When this statement is placed, if the content that is requested by Ajax changes, it will be reflected the next time the document is requested.

4.3 Read response headers

You can use the getResponseHeader and getAllResponseHeaders methods to read the HTTP headers that the server sends when responding to an AJAX request. In most cases, you don't need to care about what's in the header, because they're part of the interactive transaction between the browser and the server. The following code shows how to use this property:

<! DOCTYPE html>  

The effect chart is as follows:

Based on this figure, you can see that the development server is running the Web server software is IntelliJ idea 15.0.4, the last time to modify the apples.html document is June 27 (but the screen capture is July 5).

Related Article

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.