What are the pros and cons of Ajax? How Ajax is used correctly

Source: Internet
Author: User

This article focuses on encapsulating Ajax and asynchronous requests for Ajax, so let's take a look at this article.

Ajax

What exactly is Ajax? Ajax is a technique for creating interactive Web applications.

Ajax application scenarios include: (map) real-time updates, form validation, etc...

Advantages and disadvantages of Ajax:

Pros: 1. Implement partial update (without refresh), 2. Reduces server-side stress

Cons: 1. The browser's forward and backward mechanisms are compromised (because of the AJAX auto-update mechanism)

2. An AJAX request is more, and there will be slow page loading.

3. The level of support for search engines is low.

4.ajax security issues are not very good (can be resolved with data encryption).

First of all: if you want to use Ajax must have back-end environment support (server side).

HTTP request

There are two ways of HTTP requests

Get: Used to get data, get is to pass the data on the URL (after the URL), less storage, safety factor is relatively low.

Post: For uploading data, post security is generally better than (get better), the capacity is almost unlimited (more for the form).

Use of Ajax

There are 4 steps to using Ajax: 1. Create Ajax, 2. Connect to a server, 3. Send a request, 4. Accept the return value.

Creating Ajax

Creating AJAX must consider compatibility processing, IE6 above: New XMLHttpRequest (), ie6:new ActiveXObject ("Microsoft.XMLHTTP")

compatible processing

var xhr = null;if (window. XMLHttpRequest) {    xhr = new XMLHttpRequest ();} else{    xhr = new ActiveXObject ("Mricosoft.xmlhttp");}

Connecting to a server

The Ajax object created above is XHR, using Xhr.open ("Request Method (Get/post)", URL path, "Asynchronous/Synchronous").

The third parameter: true=== "Asynchronous, false===" synchronization. (Want to see more on the Topic.alibabacloud.comAJAX Development Manual section of the study)

When the request mode is post, the code is written as above;

When the request mode is GET, use Xhr.open ("Request Method (Get/post)", url path + "? "Request Data +," Asynchronous/Synchronous ").

Send Request

Send a request using Xhr.send ()

When the request method is get, the send request is xhr.send (null).

When the request mode is post, the sending request is xhr.send (request data).

In addition, when using post, you must add the Xhr.send (Request data)

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

Receive return value

Using AJAX would want to use an event ReadyStateChange event: When a request is sent to the server, we need to perform some response-based operations.

When the readystatechange changes, it triggers the execution of the event.

ReadyState: The status of the request, return the status code (0-4): 0 (uninitialized) Open has not been called, 1 (load) has already called send () is sending the request, 2 (loading completed) The Send method has already received all the response content, 3 (parsing) parsing response content, 4 (completion) Response content resolution completion can be used on the client.

ResponseText: Returns the requested content.

Status: Return the requested result code: Return 200 (success), return 404 (Not Found), return 5** (5 start) (server error)

Encapsulating Ajax

Parameter passing is used when encapsulating Ajax, so you must write a method to convert the object property to the AJAX request data

Here is the Ajax package, and for example:

function Ajax (options) {var xhr = null;    var params = Formsparams (Options.data); Create an object if (window.    XMLHttpRequest) {xhr = new XMLHttpRequest ()} else {xhr = new ActiveXObject ("Microsoft.XMLHTTP"); }//Connect if (Options.type = = "GET") {Xhr.open (Options.type,options.url + "?")        + Params,options.async);        Xhr.send (NULL)} else if (Options.type = = "POST") {Xhr.open (Options.type,options.url,options.async);        Xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded");    Xhr.send (params); } Xhr.onreadystatechange = function () {if (xhr.readystate = = 4 && Xhr.status = =) {options.        Success (Xhr.responsetext);        }} function Formsparams (data) {var arr = [];        For (var prop in data) {Arr.push (prop + "=" + Data[prop]);    } return Arr.join ("&"); }}ajax ({url: "a.php",//URL----> Address type: "POST",//Type---> Request method async:tRue,//async----> Sync: false, Async: true data: {//Incoming information name: "Zhang San", age:18}, Success:    function (data) {//returns the receiving information Console.log (data); }})

This is the end of this article (want to see more on the Topic.alibabacloud.comAJAX User manual section of the study), there are questions can be in the message below the question.

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.