Basic Concepts and Methods for getting started with Ajax

Source: Internet
Author: User

 

 

XMLHTTPRequest object

 

All browsers except ie support direct use of XMLHttpRequest objects. Internet Explorer creates similar objects by creating activexobject. Here we provide a packaging method to make ie versions above ie5 also have XMLHttpRequest objects, so that we can use the same creation method when using XMLHttpRequest objects:

 

(From JavaScript proficiency)

If ( Typeof XMLHttpRequest =   ' Undefined ' ){
XMLHttpRequest =   Function (){
Return   New Activexobject (
Navigator. useragent. indexof ( " MSIE 5 " ) > =   0   ?   " Microsoft. XMLHTTP " : " Msxml2.xmlhttp "
);
}
}

 

Send request

 

GET request

 

Only serialized data can be sent (see the following example)

 

The following is a simple example of sending a GET request.

 

// Create object
VaR XML =   New XMLHttpRequest ();
// Initialization
XML. Open ( " Get " , " Test.html " , True );
// Send
XML. Send ();

 

POST request

 

The post request is sent in a similar way as the GET request.

 

Request status

 

We can monitor the Request status through readystate In the XMLHTTPRequest object. Readystate is an integer value, each representing the status:

 

0 = not initialized

1 = initialized (some books marked this status as download. The actual test shows that the status has been changed to 1 after initialization and before the request is not sent)

2 = download completed

3 = interactive (partially received response)

4 = complete

 

In our Ajax application, we generally only need to use the 4-completion status.

 

When the Request status changes, the onreadystatechange event is triggered. To handle the Ajax response, bind the handler for this event.

 

Complete client example

 

The following is a complete client Ajax example based on the above content.

 

VaR XML =   New XMLHttpRequest ();

// XML. readystate not initialized is 0
XML. Open ( " Post " , " Test.html " , True );
// The initialized XML. readystate is 1.

XML. setRequestHeader ( " Content-Type " , " Application/X-WWW-form-urlencoded " );
If (XML. overridemimetype)
XML. setRequestHeader ( " Connection " , " Close " );

// Bind status change event handler
XML. onreadystatechange =   Function (){
Alert (XML. readystate );
}

XML. Send ( " ABC " );

 

Data Object format

 

Based on the characteristics of data objects, we can select an appropriate sending method.

 

Serializing

 

Using http get standard requests, that is, http://www.zhengchuyu.cn /? Name = ZCY & Nick = Donald's transmission method.

 

We need a serialized function designed for form elements and key-value pairs. (Multiple choice buttons cannot be serialized)

 

Function Serialize (){
VaR S = [];
If (A. Constructor = Array ){
// Array of form elements
For ( VaR I =   0 ; I < A. length; I ++ ){
S. Push (A [I]. Name +   " = "   + Encodeuricomponent (A [I]. Value ));
}
}
Else {
// Key-Value Pair object
For ( VaR J In A)
S. Push (J +   " = "   + Encodeuricomponent (A [J]);
}
Return S. Join ( " & " );
}

 

GET requests send serialized data

 

VaR XML =   New XMLHttpRequest ();
XML. Open ( " Get " , " Test.html? "   + Serialize (data ), True );
XML. Send ();

 

POST requests send serialized data

 

VaR XML =   New XMLHttpRequest ();
XML. Open ( " Post " , " Test.html " , True );
// Set the Content-Type header to tell the server how to parse the data we sent
XML. setRequestHeader ( " Content-Type " , " Application/X-WWW-form-urlencoded " );
// Ensure that the length of serialized data sent by the browser is correct
If (XML. overridemimetype)
XML. setRequestHeader ( " Connection " , " Close " );
// Serializing Data Transmission
XML. Send (serialize (data ));

 

XML

 

Later.

 

JSON

 

Further details

 

HTTP Response

 

As mentioned above, we can determine whether the client has received the server response by judging the readystate status. However, the server does not respond normally every time. In this case, we need to respond through the server.Code(Stored in the status variable of the returned result object) to determine the response.

 

Status Code

 

Successful response: 200 ~ 300

Response 304 not modified

The local file has no status code.

 

In addition, in Safari, if the document has not been modified since the previous request, the status code "undefined" is returned, which is strange.

 

The following is a compatible function used to determine whether the XMLHTTPRequest object is in a successful response state.

 

Function Httpsuccess (r ){
Try {
Return   ! R. Status && Location. Protocol =   " File: "  
| (R. Status > =   200   && R. Status <   300 )
| R. Status =   304
| Navigator. useragent. indexof ( " Safari " ) > =   0   &&   Typeof R. Status =   " Undefined " ;
}
Catch (E ){
Return   False ;
}
}

 

Timeout check

 

Timeout check is relatively simple, that is, to use a variable to record timeout. Before sending, use a setTimeout to set the variable to timeout after a certain period of time, and check this variable in the response function of the state change.

 

Server return data

 

The server can return data in any format. XML, HTML, and JavaScript/JSON are commonly used.

 

Get Data

 

Two important attributes of retrieving data through XMLHttpRequest: responsexml and responsetext.

 

Responsexml can be used to obtain XML, that is, this attribute can be used only when the server explicitly states "Content-Type: text/XML.

Responsetext can be used to obtain HTML and JavaScript data.

 

Resolution data of the specified type

 

The following is a function for parsing data of the specified type:

 

(From "javascript proficiency", for ease of understanding, slightly changed)

 

// Type. Optional values: XML, script, text, and HTML. Default Value: null.
Function Httpdata (R, type ){
VaR CT = R. getResponseHeader ( " Content-Type " );
VaR Data =   ! Type && CT && Ct. indexof ( " XML " ) > =   0 ;
Data = (Type =   " XML "   | Data) ? R. responsexml: R. responsetext;
If (Type =   " Script " )
Eval. Call (window, data );
Return Data;
}

 

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.