Ajax is not a technology (a good AJAX primer article) __ajax

Source: Internet
Author: User
Tags tld
Ajax is not a technology. It is actually a combination of several powerful technologies that have been in their field. Ajax Mixed up:

* Based on XHTML/CSS
* Dynamic display and interaction by Dom (Document Object Model)
* Data exchange and processing through XML and XSLT
* Use JavaScript to integrate the above technologies

XMLHttpRequest is a key technology for Ajax, but XMLHttpRequest is not the standard for the consortium. The vast amount of functionality it currently completes will be transitioned to the new project "DOM Level 3 Load and Save" standard in the consortium. The Xmlhttpreques,web page allows you to get feedback and requirements from the Web server without reloading the page. Users will stay on the same page without noticing that the script might require a page in the background or send data to the server. Google suggest is a dynamic web interface built with a XMLHttpRequest object: When you start typing in Google's search box, a JS script sends letters to a server and returns a list of suggestions from the server. The "DOM Level 3 Load and Save" standard includes some similar features, but these are not implemented in any browser. So for now, if you need to send an HTTP request from a browser, you still have to use the XMLHttpRequest object. Javascript also relies on XMLHttpRequest to get XML. For different browsers, the way to create a XMLHttpRequest object is somewhat dissimilar, with a combination of scripting that basically satisfies the need to create XMLHttpRequest in various browsers.

<script type= "Text/javascript" >
var xmlHttp;
function Creatxmlhttprequest () {
if (window. ActiveXObject) {
XmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");
}
else if (window. XMLHttpRequest) {
XmlHttp = new XMLHttpRequest ();
}
else {
Return
}
}

The XMLHttpRequest object contains methods and attributes, regardless of whether they are used or not.

Methods (method)

Abort ()
Cancels the current request

Cancel the current request

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

Returns the complete HTTP header information as a string

getResponseHeader ("Headername")
Returns the value of the specified HTTP header

Returns the specified HTTP header information value

Open ("Method", "URL", Async, "uname", "pswd")
Specifies the method, URLs, and other optional attributes of a request

Specify the distribution, URL, and any other attributes for a request.

The method parameter can have a value of ' get ', ' post ', or ' put ' (use ' get ' when requesting data and use ' post ' when Sendi Ng data (especially if the length of the the data is greater than bytes.

The method parameter can be "get", "post", or one of the "put" (Request data to be more with get and post data [especially data longer than 512 bytes)]

The URL parameter may is either a relative or complete URL.

The URL can be either an absolute path or a relative path.

The Async parameter specifies whether the request should be handled asynchronously or not. True means that script processing carries in after the Send () method, without waiting for a response. False means that script waits for a response before continuing script processing

The asynchronous parameter indicates whether the request should be processed. Set to True means that the script will continue to execute after the Send () method, without waiting for the server to respond. "False" is the script must wait for a response from the server before it can continue execution.

Send (content)
Sends the request

Send Request

setRequestHeader ("label", "value")
Adds a Label/value pair to the HTTP header to is sent

Properties Property

onreadystatechange*:
An event handler for "an event", "fires at every", typically a call to a JavaScript function.
This is the most important attribute, and the event handling for each state change is often used to trigger a JavaScript run.

ReadyState:
Returns the state of the object:
The returned Status object:

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

ResponseText:
Returns the response as a string
Returns as a string

Responsexml:
Returns the response as XML. This property returns a XML Document object, which can be examined and parsed using the "a", "DOM node Tree" methods and Propert ies
Returned as XML, this property returns an XML document object that can be parsed and validated using the DOM point tree methods and attributes of the consortium.

Status:
Returns the status as a number (e.g. 404 for ' not Found ' or ' for ' OK ')
Returns 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 a status as a string (for example, "not found" or "good")

Step one: "Please!"-how to send an HTTP request.

Sending an HTTP request is the key, so let's summarize the steps, which are 4 step:

1. Obtain a XMLHttpRequest instance, either by creating, or by accessing an existing XMLHttpRequest object instance.

<script type= "Text/javascript" >
var xmlHttp;
function Creatxmlhttprequest () {
if (window. ActiveXObject) {
XmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");
}
else if (window. XMLHttpRequest) {
XmlHttp = new XMLHttpRequest ();
}
else {
Return
}
}

2. Next, decide what you want to do when you receive a response from the server. This tells the HTTP request object which JavaScript function to use to handle the response. You can set the object's onReadyStateChange property to the name of the function of the javascript you want to use.

Xmlhttp.onreadystatechange = Handlestatechange;

Note: There is no parentheses after the function name, and there is no need to pass arguments.

3. After defining how to handle the response, the request is sent. You can invoke the open () and send () methods of the HTTP request class, such as:

Xmlhttp.open ("Get", "Simpleresponse.xml", true);
Xmlhttp.send (NULL);

Some of the arguments behind open () are explained here. The first parameter is the HTTP request way –get,post,head or the way that any server supports that you want to invoke. This argument is capitalized according to the HTTP specification, otherwise some browsers, such as Firefox, may not be able to process the request. The second parameter is the URL of the request page. The page cannot be a third party domain name due to the limitations of its own security features. At the same time must ensure that all pages are using the exact domain name, otherwise call open () will get "Permission denied" error prompts. A common mistake is to use domain.tld when visiting a site, but to use "www.domain.tld" when requesting a page. The third parameter sets whether the request is asynchronous mode. If it is ture, the JavaScript function will continue to execute without waiting for the server to respond. This is the "asynchronous" in "AJAX".

4. Send a request to the server. The Send () method sends the request to the specified target resource. The Send () method allows a parameter, either a string or a DOM object. This parameter is transmitted to the destination URL as part of the request itself. When the Send () method contains parameters, it is necessary to determine that the first parameter in the open () method is "POST". If no data is to be sent as part of the request itself, use "null", as we have in our example.

Step 2– "Receive!"-Process Server response

When sending a request, provide a JavaScript function name that specifies the response to be processed, and we have defined this function (Handlestatechange) at the 2nd step. Let's see what the function of this function is. The function first checks the state of the request, and if the status value is 4, it means that a full server response has been received and you will be able to handle the response.

if (xmlhttp.readystate = = 4) {
Everything is good, the response is received
} else {
Still not ready
}

The readystate values are as follows:

* 0 (uninitialized)
* 1 (loading)
* 2 (Load complete)
* 3 (Interactive)
* 4 (complete)

The function then checks the status value of the HTTP server response. Full state values can be found in the Web site, and we will focus on the response with a value of (OK).

if (Xmlhttp.status = = 200) {
perfect!
} else {
There was a problem with the request,
For example the "response may" a 404 (Not Found)
or (Internal Server Error) Response codes
}

After checking the status value of the request and the HTTP status value of the response, you can process the data from the server. There are two ways to get this data:

xmlhttp.responsetext– returns the response of the server as a text string
xmlhttp.responsexml– returns the response as a XmlDocument object. Processing XmlDocument objects can be used with JavaScript DOM functions

To sort out the code for step 2 is to process the server's corresponding function (Handlestatechange):

function Handlestatechange () {
if (xmlhttp.readystate = = 4) {
if (Xmlhttp.status = = 200) {
Alert ("The Server repilied with:" + xmlhttp.responsetext);
}
}
}

Step 3– "Everything is ready!"-simple example

We will now complete the whole 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!", and then we "alert ()" Simpleresponse.xml the contents of the file.

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 strict//en"
"Http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" >
<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);
}
}
}
</script>
<body>
<form action= "#" >
<input type= "button" value= "Start Basic asynchronous Request" onclick= "startrequest ();" />
</form>
</body>
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.