Ajax working principle and advantages and disadvantages detailed _ajax related

Source: Internet
Author: User

AJAX is a technique for creating fast-moving web pages. AJAX enables asynchronous updating of Web pages by making a small amount of data exchange in the background with the server. This means you can update portions of a Web page without reloading the entire page.

The technology that Ajax contains

We all know that Ajax is not a new technology, but a combination of several original technologies. It is a combination of the following technologies.

Use CSS and XHTML for presentation.

Use the DOM model for interactive and dynamic display.

Use XMLHttpRequest to communicate asynchronously with the server.

Use JavaScript to bind and invoke.

In the above technologies, all other technologies, except XMLHttpRequest objects, are based on web standards and have been widely used, and xmlhttprequest, though not yet accepted by the consortium, is a fact standard, Because almost all of the mainstream browsers now support it.

Second, how to create Ajax

The principle of Ajax is simply to send an asynchronous request to the server via the XMLHttpRequest object, get the data from the server, and then use JavaScript to manipulate the DOM and update the page. One of the most critical steps is getting the request data from the server. Native creation Ajax can be divided into the following four steps.

1. Create XMLHttpRequest Objects

All modern browsers (ie7+, Firefox, Chrome, Safari, and Opera) have built-in XMLHttpRequest objects.

To create the syntax for a XMLHttpRequest object:

var xhr = new XMLHttpRequest ();

Older versions of Internet Explorer (IE5 and IE6) use ActiveX objects:

var xhr = new ActiveXObject ("Microsoft.XMLHTTP");

To respond to all modern browsers, including IE5 and IE6, check to see if the browser supports XMLHttpRequest objects. If supported, the XMLHttpRequest object is created. If not supported, create ActiveXObject:

var xhr;
if (XMLHttpRequest) {
xhr = new XMLHttpRequest ();
} else{
xhr = new ActiveXObject ("Microsoft.XMLHTTP");
}

2. Prepare the request

Initializes the XMLHttpRequest object, accepting three parameters:

Xhr.open (Method,url,async);

The first parameter represents the string of the request type, and its value can be either get or post.

GET Request:

Xhr.open ("Get", demo.php?name=tsrot&age=24,true);

POST request:

Xhr.open ("POST", demo.php,true);

The second parameter is the URL to send the target as a request.

The third argument is true or false, indicating whether the request was sent in an asynchronous or synchronized mode. (default is true, generally not recommended for false)

False: A request from synchronous mode pauses the execution of all JavaScript code, knowing that the server is responding, and that the page hangs if the browser fails when it connects to the network or when the file is downloaded.
True: A request sent by an asynchronous pattern that requests the object to send and receive data while the browser can continue to load the page and execute other JavaScript code

3, send the request

Xhr.send ();

In general, the parameters submitted using Ajax are mostly simple strings that can be written directly to the URL parameter of the open method using the Get method, where the parameter of the Send method is null or empty.

GET Request:

Xhr.open ("Get", demo.php?name=tsrot&age=24,true);
Xhr.send (NULL);

POST request:

If you need to POST data like an HTML form, use setRequestHeader () to add an HTTP header. Then specify the data you want to send in the Send () method:

Xhr.open ("POST", demo.php,true);
Xhr.setrequestheder ("Content-type", "Application/x-www-form-urlencoded;charset=utf-8");
Xhr.send ("name=" +username+ "&age=" +userage);

4, processing response

Xhr.onreadystatechange = function () {
if (xhr.readystate = = 4 && xhr.status =) {
Console.log ( Xhr.responsetext);
}

onReadyStateChange Event:

When the request is sent to the server, we need to perform some response based tasks. Whenever the readyState changes, the onReadyStateChange event is triggered.

ReadyState Properties:

0: The object has been created, but the open () method has not been invoked yet.

1: The Open () method has been called, but the request has not been sent.

2: The request has been sent, the title and status have been received and available.

3: Received a response from the server.

4: The request data is received, indicating that the request has been completed.

Status property:

: "OK"

404: Page Not Found

ResponseText: Get response data in string form

Responsexml: Get response data in XML form

The return value is typically a JSON string that can be converted to a JSON object using Json.parse (Xhr.responsetext).

5. Complete Example

Demo.html

var xhr;
if (XMLHttpRequest) {
xhr = new XMLHttpRequest ();
} else{
xhr = new ActiveXObject ("Microsoft.XMLHTTP");
Xhr.open ("Get", "./data.json", true);
Xhr.send ();
Xhr.onreadystatechange = function () {
if (xhr.readystate = = 4 && xhr.status =) {
Console.log ( Json.parse (xhr.responsetext). name);
}

Data.json

{
' name ': ' Tsrot ',
' age ':
}

Third, AJAX application scenarios

Scene 1. Data validation

Scene 2. Fetch data on Demand

Scene 3. Automatically update pages

Iv. Ajax Pros and cons

Advantages:

1, the page does not refresh, the user experience is good.

2, asynchronous communication, faster response capabilities.

3, reduce the redundant request, reduce the server burden

4, based on standardized and widely supported technology, do not need to download plug-ins or small programs.

Disadvantages:

1, Ajax killed the back button, that is, the browser backward mechanism of the damage.

2, there are certain security issues.

3, the search engine support is weaker.

4, the failure of the program's abnormal mechanism.

5, can not use the URL direct access.

The above is a small set to introduce the AJAX working principles and advantages and disadvantages of detailed, hope to help everyone, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.