The basic principle of implementing asynchronous Ajax with pure JavaScript

Source: Internet
Author: User
Tags html form

Ajax is actually the XMLHttpRequest object and the DOM, (X) HTML and CSS abbreviations, used to summarize the asynchronous loading of page content technology.

Ajax instances

The HTML code is as follows, containing a H5 title and a button:

The JS code is as follows:

The core object in the code above is XMLHttpRequest, which is the technical basis of Ajax. All modern browsers support
XMLHttpRequest objects (IE5 and IE6 use ActiveXObject). XMLHttpRequest
Used to exchange data with the server in the background. This means that you can update a part of a webpage without reloading the entire page.

JavaScript Technology Group: 499415298

Create a XMLHttpRequest Object

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

Syntax for creating XMLHttpRequest objects:
Variable=new XMLHttpRequest ();
Older versions of Internet Explorer (IE5 and IE6) use ActiveX objects:
Variable=new ActiveXObject ("Microsoft.XMLHTTP");

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

Ajax requests to send requests to the server

To send the request to the server, we use the open () and send () methods of the XMLHttpRequest object:

Xmlhttp.open ("GET", "Test1.txt", true);

Xmlhttp.send ();

GET or POST?

GET is simpler and faster than POST, and can be used in most cases.

However, use the POST request in the following cases:

    • Unable to use cache file (must update file or database on server)

    • Send a large amount of data to the server (POST has no data volume limit)

    • Post is more stable and more reliable than GET when sending user input with unknown characters

GET Request

A simple GET request:

Xmlhttp.open ("GET", "demo_get.asp?t=" + math.random (), true);

Xmlhttp.send ();

In the example above, you might get the results of the cache.

To avoid this situation, add a unique ID to the URL:

Xmlhttp.open ("GET", "demo_get.asp?t=" + math.random (), true);

Xmlhttp.send ();

If you want to send information through the GET method, add information to the URL:

Xmlhttp.open ("GET", "Demo_get2.asp?fname=bill&lname=gates", true);

Xmlhttp.send ();

POST Request

A simple POST request:

Xmlhttp.open ("POST", "demo_post.asp", true);

Xmlhttp.send ();

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:

Xmlhttp.open ("POST", "ajax_test.asp", true);

Xmlhttp.setrequestheader ("Content-type", "application/x-www-form-urlencoded");

Xmlhttp.send ("Fname=bill&lname=gates");

URL-Files on the server

The URL parameter of the Open () method is the address of the file on the server:

The file can be any type of file, such as. txt and. xml, or server script files, such as. asp and. PHP (the ability to perform tasks on the server before the response is returned).

Asynchronous-True or False?

AJAX refers to asynchronous JavaScript and XML (asynchronous JavaScript and XML).

The async parameter of the open () method must be set to True if the XMLHttpRequest object is to be used with AJAX:

For Web developers, sending asynchronous requests is a huge step forward. Many tasks performed on the server are quite time consuming. This may cause the application to hang or stop before AJAX occurs.

Instead of waiting for a response from the server, Ajax,javascript does:

    • Execute additional scripts while waiting for the server to respond

    • Handle responses when they are ready

Async = True

When using Async=true, specify the function to be executed when responding to the ready state in the onReadyStateChange event:

JavaScript Technology Exchange Group: 499415298Async = False

To use Async=false, change the third parameter in the open () method to False:

Xmlhttp.open ("GET", "Test1.txt", false);

We do not recommend the use of Async=false, but for some small requests it is also possible.

Keep in mind that JavaScript waits until the server responds in readiness to continue. If the server is busy or slow, the application hangs or stops.

Xmlhttp.open ("GET", "Test1.txt", false);

Xmlhttp.send ();

document.getElementById ("Mydiv"). Innerhtml=xmlhttp.responsetext;

Server answer

To obtain a response from the server, use the ResponseText or Responsexml property of the XMLHttpRequest object.

Where ResponseText is used to get the data in text or JSON format, and Responsexml is used to get an XML document.

ResponseText Property

If the response from the server is not XML, use the ResponseText property.

The ResponseText property returns a response in the form of a string, so you can use:

document.getElementById ("Mydiv"). Innerhtml=xmlhttp.responsetext;

In the case of JSON data, you can use:

var result = Xmlhttp.responsetext;

var person = eval ("(" + result + ")");

alert (person.name);//Read JSON data

The JSON-encoded data returned needs to be converted to a JS object using the Eval statement, which can then be used to get its properties.

Responsexml Property

If the response from the server is XML and needs to be parsed as an XML object, use the Responsexml property:

Request the Books.xml file and parse the response:

The pros and cons of Ajax

Like any technology, Ajax has its pros and cons.

The advantage is that you can reduce page refresh requests and implement local data updates.

The disadvantage is that the accessibility of the search engine is not friendly, in addition, if the misuse of AJAX requests, but will lead to unnecessary requests, such as generally through the asynchronous request to load the article content is inefficient, originally as long as 1 requests, was split into 2 requests (load the page frame one time, load the content).

We should use Ajax where asynchronous refreshes are really needed.

JavaScript Technology Exchange Group: 499415298, welcome beginner and advanced partner.

The basic principle of implementing asynchronous Ajax with pure JavaScript

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.