AJAX (usage Summary-Elite edition)

Source: Internet
Author: User
Tags event listener

1. What is Ajax?

ajax:asynchronous JavaScript and XML: Asynchronous JavaScript and XML.

Ajax is a technique used to improve the user experience, essentially using a special object built into the browser (XMLHttpRequest) to asynchronously (that is, when a request is sent, the browser does not destroy the current page, and the user can continue to do other things on the current page) to send a request to the server, The current page is partially updated with the data returned by the server (no longer a full page, just part of the data, typically returned with text or XML).

After using AJAX technology, the page is not refreshed and the user's actions are not interrupted.

2. Ajax objects

(1) How to get Ajax Object ?

XMLHttpRequest is not standardized, to differentiate between browsers:

function getxhr ()

{

var xhr;

if (window. XMLHttpRequest) {

xhr = new XMLHttpRequest (); //non-IE browser

}else{

xhr = new ActiveXObject (' microsoft.xmlhttp '); //IE browser

}

}

(2) Ajax properties of the object

A. onreadystatechange: Binding an event handler (that is, registering a listener)

When the readystate value of an Ajax object has changed (for example,

From 0-->1), a ReadyStateChange event is generated.

B. ResponseText: Get the text returned by the server

C. responsexml: Get the XML DOM object returned by the server

D. Status: Get State code

E. readyState: Returns the status of the Ajax object communicating with the server. The return value is a value of type number, and different values represent different meanings:

0: (for initialization)-the object has been established but not initialized (the open method has not been called)

1: (Initialize)-object has been established, the Send method has not been called

2: (send data)--The Send method has been called

3: (in data transfer)--accepted partial data

4: (End of response)-all data received

(3) Ajax basic steps for programming

1) Get Ajax object (XMLHttpRequest)

2) use XMLHttpRequest to send requests to the server

3) processing requests on the server side

4) in the listener, handle the response returned by the server

1) Get Ajax object (XMLHttpRequest)

var xhr = getxhr ();

2) Send request

Xhr.open ( request method , request address , asynchronous or synchronous );

Request Method: Get/post

Request Address: If it is a GET request, the request parameter is added to the back of the request address.

True indicates an asynchronous request: When the Ajax object sends the request, the user can

Page to do other operations. asynchronous is generally used .

False indicates a synchronous request: When the Ajax object sends the request, the browser locks

Front page, the user needs to wait for processing to complete before doing the next step.

Mode one: Get request

var xhr = getxhr ();

xhr.open (' Get ', ' Check_name.action?name=zs ', true);

XHR.ONREADYSTATECHANGE=F1;

Xhr.send (NULL);

Mode two: POST request

var xhr = getxhr ();

Xhr.open (' Post ', ' check_username.action ', true);

// If you are sending a post request, the encoding format of the message header needs to be set to "Application "

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

XHR.ONREADYSTATECHANGE=F1;

Xhr.send (' username= ' + $F (' username '));

Attention:

Because as required by the HTTP protocol, if a POST request is sent, there should be a message header Content-type inside the request packet. However, the Ajax object does not default, so you need to call the setRequestHeader method.

3) Write server-side code, the server side generally do not need to return the full page, only need to return some of the data, such as a simple string.

4) Writing Listeners

Function F1 () {

if (xhr.readystate = = 4) {

Get the data returned by the server

var txt = xhr.responsetext;

DOM Operations

}

}

<script type= "Text/javascript" >

function $ (ID) //definition of common functions of Ajax

{

return document.getElementById (ID);

}

function $F (ID) {

return document.getElementById (ID). value;

}

function getxhr () //Get XMLHttpRequest

{

var xhr;

if (window. XMLHttpRequest) {

XHR = new XMLHttpRequest (); //non-IE browser

}else{

XHR = new ActiveXObject (' microsoft.xmlhttp '); //IE browser

}

}

GET Way :

function Check_name ()

{

First step: Get Ajax objects

var xhr = getxhr ();

Step two: Send the request

xhr.open (' Get ', ' check_name.action?name= ' + $F (' uname '), true);

Step three: Ajax functions: Registering an Event listener

Xhr.onreadystatechange = function ()//This function is an anonymous function, an intrinsic function

{

Only the readystate value of the Ajax object is 4 o'clock to get the data returned by the server

if (xhr.readystate = = 4)

{

Get the text data returned by the server

var txt = xhr.responsetext;

Update page

${' name_msg '}.innerhtml = txt;

}

}

$ (' name_msg '). InnerHTML = ' verifying .... ';

Fourth step: Send the request

Xhr.send (NULL);   

}

POST Way :

function Check_name ()

{

First step: Get Ajax objects

var xhr = getxhr ();

Step two: Send the request

xhr.open (' Post ', ' check_name.action ', true);

xhr.setrequestheader ('content-type', 'application/x-www-form-urlencoded ');

Step Three: Ajax functions

Xhr.onreadystatechange = function ()//This function is an anonymous function, an intrinsic function

{

Only the readystate value of the Ajax object is 4 o'clock to get the data returned by the server

if (xhr.readystate = = 4)

{

Get the text data returned by the server

var txt = xhr.responsetext;

Update page

${' name_msg '}.innerhtml = txt;

}

}

$ (' name_msg '). InnerHTML = ' verifying .... ';

Fourth step: Send the request

Xhr.send (' username= ' + $F (' uname '));

   }

with GET or is POST ?

GET is simpler and faster than POST, and can be used in most cases. However, use the POST request in the following cases:

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

(2) Send a large amount of data to the server (POST no data limit)

(3) When sending user input with unknown characters, POST is more stable and more reliable than GET.

Ajax coding problems in programming

(1) Send a GET request:

The Ajax object built into the IE browser uses GBK encoding for Chinese parameters, while other browsers (Firefox,chrome) use UTF8 encoding.

The server side uses Iso-8859-1 to decode by default.

Solution:

1) The server decodes the parameters in the GET request using the specified encoding format.

For example: for Tomcat, you can modify conf/server.xml ( add uriencoding= "UTF-8")

That is: Tell the server to encode/decode with UTF-8 for all get requests

2) for the request address, use the encodeURI function for uniform encoding (UTF-8)

The function: the "UTF-8" encoding of the Chinese in the request address.

var uri = ' check_username.action?username= ' + $F {' username '};

var uri2 = encodeURI (URI); Encode, spoof browser, prevent garbled

xhr.open (' Get ', uri2, true);

Summarize:

Resolve GET request Pass Chinese parameter garbled problem:

(1) Modify the Server.xml under Tomcat and add it after Connection      

uriencoding= "UTF-8", tell the server, for Get the data in the request, using the UTF-8 decoding.

(2) in Ajax before sending a get request, add :

var uri = ' check_uname.action?uname= ' + $F {' uname '};

Xhr.open (' Get ', encodeURI (URI), true);

with the top 2 step, can result Ajax in Get Request Parameters Chinese garbled problem (yes, so the browser applies ).

(2) Send post

All Ajax objects built into the browser will be encoded using UTF-8.

Solution:

Request.setcharacterencoding ("Utf-8");

Caching issues in AJAX applications:

When using the IE browser, the browser caches the data if the request is made using the Get method.

Thus, when this request is sent again, if the request address is not changed, ie does not really send the request to the server, but instead displays the previously cached data to the user.

Workaround 1: Use post to send the request.

Workaround 2: Add a random number after the request address:

xhr.open (' Get ', ' some?tt= ' + math.random (), true);

5. Send a sync request

Xhr.open (' Post ', ' check_username.do ', false);

AJAX (usage Summary-Elite edition)

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.