Ajax is not a technology (a good entry to Ajax)

Source: Internet
Author: User
Tags tld

Ajax is not a technology. It is actually a combination of several popular technologies in their respective fields. Ajax mixed:

The following is a reference clip * Based on XHTML/CSS.
* Dom (Document Object Model) enables Dynamic Display and Interaction
* Data exchange and processing through XML and XSLT
* Use JavaScript to integrate the above technologies

XMLHttpRequest is a key Ajax technology, but XMLHttpRequest is not W3C standard. A large number of features it has completed will be transitioned to the W3C new project Dom Level 3 load and save standard. With xmlhttpreques, the web page can receive feedback and requirements from the Web server without reloading the page. The user will stay on the same page without notice that the script may require a page in the background or send data to the server. Google suggest is a dynamic web interface created using the XMLHTTPRequest object: When you start typing in the Google search box, a js script sends letters to a server and returns a column of suggestions from the server. The W3C "dom Level 3 load and save" Standard contains similar functions, but these cannot be implemented in any browser. So now, if you need to send an HTTP request from a browser, you still need to use the XMLHTTPRequest object. Javascript also relies on XMLHttpRequest to obtain XML. For different browsers, the method for creating XMLHttpRequest objects is somewhat different. After combining multiple scripts, the following scripts can basically meet the needs for creating XMLHttpRequest in various browsers.

Code Fragment

  < Script Type = "Text / JavaScript" >  
VaR XMLHTTP;
Function Creatxmlhttprequest () {
If (Window. activexobject) {
XMLHTTP= NewActivexobject ("Microsoft. XMLHTTP ");
} // 51aspx.com
Else   If (Window. XMLHttpRequest) {
XMLHTTP= NewXMLHttpRequest ();
}  
Else   {
Return;
}  
}
</ Script >

The XMLHTTPRequest object contains some methods and attributes, regardless of them.

Methods (method)

Code snippet abort ()
Cancels the current request

Cancel current request

Code snippet getAllResponseHeaders ()
Returns the complete set of HTTP headers as a string

Returns complete HTTP header information in the form of a string

Code snippet getResponseHeader ("headername ")
Returns the value of the specified HTTP Header

Returns the specified HTTP header value.

Code snippet open ("method", "url", async, "uname", "pswd ")

Specifies the method, URL, and other optional attributes of a request

Specify any attributes of the issuance, URL, and others for a request.

The method parameter can have a value of "get", "post ", or "put" (use "get" when requesting data and use "Post" when sending data (especially if the length of the data is greater than 512 bytes 51aspx.com.

The method parameter can be "get", "Post", or "put" (The request data is more than get and the post is used to send data [especially the data with a length greater than 512 bytes]).

The URL parameter may be either a relative or complete URL (http://www.51aspx.com ).

The URL can be an absolute or relative path.

The async parameter specifies whether the request shocould be handled asynchronously or not. true means that script processing carries on after the send () method, without waiting for a response (51aspx.com ). false means that the script waits for a response before continuing Script Processing

Asynchronous parameters indicate whether the request should be processed. Setting "true" means that the script continues to be executed after the send () method ends, without waiting for the response from the server. "False" indicates that the script can be executed only after the server responds.

Code snippet send (content)
Sends the request

Send request

Code snippet setRequestHeader ("label", "value ")

Adds a label/value pair to the HTTP header to be sent

Properties

Onreadystatechange *:
An event handler for an event that fires at every state change, typically a call to a JavaScript function.
This is the most important attribute. Event Processing for each state change is often used to trigger a javascript operation.

Readystate:
Returns the state of the object:
Returned status object:

* 0 = uninitialized [initialization]
* 1 = loading [loading]
* 2 = loaded [Loaded]
* 3 = interactive [interaction]
* 4 = complete [completed]

Responsetext:
Returns the response as a string
Returns a string

Responsexml:
Returns the response as XML. This property returns an XML document object, which can be examined and parsed using W3C Dom node tree methods and properties (51aspx.com)
Returned in XML format. This attribute returns an XML document object, which can be parsed and verified by W3C Dom Vertex Tree methods and attributes.

Status:
Returns the status as a number (e.g. 404 for "not found" or 200 for "OK ")
Return the status as a number (for example, 404 is "not found" or 200 is "good")

Statustext:
Returns the status as a string (e.g. "Not Found" or "OK ")
Returns the status in string format (for example, "no" or "good" is found)

Step 1: "Please !" -How to send an HTTP request?

The key to sending an HTTP request is to summarize the steps. There are four steps in total:

1. Get an XMLHttpRequest instance. You can create it or access an existing XMLHTTPRequest object instance.

Code snippet <SCRIPT type = "text/JavaScript">
VaR XMLHTTP;
Function creatxmlhttprequest (){
If (window. activexobject ){
XMLHTTP = new activexobject ("Microsoft. XMLHTTP ");
}
Else if (window. XMLHttpRequest ){
XMLHTTP = new XMLHttpRequest ();
}
// 51aspx.com
Else {
Return;
}
}
</SCRIPT>

2. Next, you need to decide what to do when you receive the response from the server. This tells the HTTP request object which JavaScript function is used to process the response. You can set the onreadystatechange attribute of the object to the name of the JavaScript function to be used.

Code snippet XMLHTTP. onreadystatechange = handlestatechange;

Note: There are no parentheses after the function name, and no parameters need to be passed.

3. After defining how to handle the response, you need to send the request. You can call the open () and send () Methods of the HTTP request class, for example:

Code snippet XMLHTTP. Open ("get", "simpleresponse. xml", true );
XMLHTTP. Send (null );

The parameters following open () are explained here. The first parameter is the HTTP Request Method-Get, post, head or the method you want to call supported by any server. According to HTTP specifications, this parameter must be capitalized; otherwise, Some browsers (such as Firefox) may not be able to process requests. The second parameter is the URL of the Request page. Due to security restrictions, this page cannot be a third-party domain name page. Make sure that the correct domain name is used on all pages. Otherwise, an error message "Permission denied" is displayed when you call open. A common error is that domain. TLD is used to access the website, but "www. domain. TLD" is used to request the page ". The third parameter sets whether the request is in asynchronous mode. If it is true, the JavaScript function will continue to be executed without waiting for the server to respond. This is "Asynchronous" in "Ajax ".

4. send a request to the server. The send () method sends a request to the specified target resource. The send () method allows a parameter, which can be a string or a DOM object. This parameter is transmitted to the destination URL as part of the request. When the send () method contains parameters, make sure that the first parameter in the open () method is "Post ". If no data is sent as part of the request itself, use "null", as we used in the example.

Step 2-"receive !" -Process Server Response

When sending a request, provide the specified JavaScript function name for processing the response. In Step 1, we have defined this function (handlestatechange ). Let's take a look at the functions of this function. First, the function checks the Request status. If the value is 4, it means that a complete server response has been received and you can process the response.

Code snippet if (XMLHTTP. readystate = 4 ){
// Everything is good, the response is already ed
} Else {
// Still not ready
}

The value of readystate is as follows:

0 (not initialized)
1 (loading)
2 (loaded)
3 (in interaction)
4 (finished)

Then, the function checks the status value of the HTTP server response. For the complete status values, see W3C site. We focus on the response with a value of 200 (OK.

Code snippet if (XMLHTTP. Status = 200 ){
// Perfect!
} Else {
// There was a problem with the request,
// For example the response may be a 404 (not found)
// Or 500 (internal server error) Response codes
}

After checking the Request status value and response HTTP status value, you can process the data obtained from the server. There are two ways to obtain the data:

XMLHTTP. responsetext-returns the server response in the form of a text string
XMLHTTP. responsexml-returns a response as an xmldocument object. You can use Javascript DOM functions to process xmldocument objects.

Sort out the code in step 2 to process the corresponding server function (handlestatechange ):

Code snippet function handlestatechange (){
If (XMLHTTP. readystate = 4 ){
If (XMLHTTP. Status = 200 ){
Alert ("the server repilied with:" + XMLHTTP. responsetext );
}
}
}

Step 3-"Everything is ready !" -Simple instance

We will now complete the entire process once.

Send a simple HTTP request. We use JavaScript to request an XML file, simpleresponse. xml. The text content of the file is "Hello from the server !", Then the content of the "alert ()" simpleresponse. xml file is used.

Code snippet <! Doctype HTML public "-// W3C // dtd xhtml 1.0 strict // en"
"Http://www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd">
<HTML xmlns = "http://www.w3.org/5o/xhtml">
<Head>
<Title> simple XMLHttpRequest </title>
<SCRIPT type = "text/JavaScript">
VaR XMLHTTP;
Function createxmlhttprequest (){
If (window. activexobject ){
XMLHTTP = new activexobject ("Microsoft. XMLHTTP ");
}
Else if (window. XMLHttpRequest ){
XMLHTTP = new XMLHttpRequest ();
}
}

function startrequest () {
createxmlhttprequest ();
XMLHTTP. onreadystatechange = handlestatechange;
XMLHTTP. open ("get", "simpleresponse. XML ", true);
XMLHTTP. send (null);
}

function handlestatechange () {
If (XMLHTTP. readystate = 4) {
If (XMLHTTP. status = 200) {
alert ("the server replied with:" + XMLHTTP. responsetext );
}< BR >}< br>






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.