JavaScript Learning Notes (vii) AJAX and HTTP status Code _ Basics

Source: Internet
Author: User
Tags button type http request

Ajax and its working principle

AJAX is an exchange of data with the server without refreshing the Web page technology, the first by Google in Google Maps used, and quickly swept.

Ajax cannot be cross-domain, and you can use document.domain= ' a.com ' If you need to cross domains, or use a server Agent to XMLHttpRequest files

Ajax is based on existing Internet standards and uses them jointly:

XMLHttpRequest objects (asynchronously exchanging data with the server)
Javascript/dom (Information display/interaction)
CSS (defines styles for data)
XML (as a format for transforming data)

Creating XMLHttpRequest Objects

All modern browsers (ie7+, Firefox, Chrome, Safari, and Opera) have built-in XMLHttpRequest objects.

To create an Ajax object:

IE6 above
var oajax = new XMLHttpRequest ();

IE6
var oajax =new ActiveXObject ("Microsoft.XMLHTTP")
Connecting to a server

Oajax.open (method, URL, asynchronous)
As we all know, Ajax is "Asynchronous JavaScript and XML" (Asynchronous JavaScript and XML), a Web development technology that creates interactive Web applications. So Ajax is inherently working in asynchronous mode (asynchronous to True, sync false)

Synchronous and asynchronous

Synchronization refers to the way in which the next packet is communicated after the sender sends the data and the receiver sends back the response.
Asynchronous refers to the way in which the sender sends the data, waits for the receiver to send back the response, and then sends the next packet's communication.
(In simple words: synchronization is only one thing to do, and asynchronous is to do many things at the same time)

Send a request send ()

Copy Code code as follows:

<script type= "Text/javascript" >
function Getdoc () {
var xmlhttp;
if (window.xmlhttprequest) {
Xmlhttp=new XMLHttpRequest ();
}
else{
XMLHTTP = new ActiveXObject ("Microsoft.XMLHTTP");//for IE6
}
Xmlhttp.onreadystatechange = function () {
if (xmlhttp.readystate==4&&xmlhttp.status==200) {
document.getElementById ("MyId"). Innerhtml=xmlhttp.responsetext;
}
}
Xmlhttp.open ("Get", index.php,true);
Xmlhttp.send ();
}
</script>
<body>
<button type= "button" onclick= "Getdoc ()" > Request data </button>
</body>

Get or POST?

Get is simpler and faster than POST, and can be used in most cases.

However, use POST requests in the following situations:

Unable to use cache file (update file or database on server)
Send large amounts of data to the server (POST no data limit)
Post is more stable and reliable than get when sending user input with unknown characters
Receive return information

Oajax.onreadystatechange = function () {//event handler to invoke when request state changes

alert (oajax.readystate);

}
A ReadyStateChange event is triggered whenever the value of the ReadyState property changes. You can use this event to detect readystate values after each state change. Typically, we are only interested in a phase with a readystate value of 4, since all data is ready, but you must specify the onReadyStateChange event handler before calling open () to ensure cross-browser compatibility. Here's an example:

Copy Code code as follows:

var xhr = createxhr ();
Xhr.onreadystatechange = function () {
if (xhr.readystate = = 4) {
if ((Xhr.status >= && xhr.status <) | | xhr.status = = 304) {
alert (Xhr.statustext);
} else {
Alert ("Request was unsuccessful:" + xhr.status);
}
}
};
Xhr.open ("Get", "Example.txt", true);
Xhr.send (NULL);

XHR objects

When a Xhr object sends an HTTP request to the server, it goes through several states until the request is processed before receiving a response. ReadyState is the state attribute of the XHR request, which itself has 5 property values:

0 (uninitialized) has not yet called the Open () method
1 (load) called Send () method, sending request
2 (load complete) Send () method completed, received all response content
3 (parsing) parsing response content
4 (complete) Response content parsing completed, you can use the client
Status

The Status property represents the response status code returned from the server. For example: 200 indicates success, and 404 indicates that it was not found.

1 Word header: message. This type of status code that represents the request has been accepted and needs to be processed.
2 Word head: success. This type of status code that represents a request that has been successfully received, understood, and accepted by the server.
3-Character Header: redirect. This type of status code represents the need for the client to take further action to complete the request.
4-Word Header: Client error. This type of status code indicates that the client may appear to have an error, preventing the server from processing.
5-Word Header: Server error. This type of status code indicates that the server has an error or an abnormal state in the process of processing the request

Additional: Detailed HTTP status code

StatusText

StatusText is a response to the returned text message and can only be used if the readystate value is 3 or 4. The view Access StatusText property throws an exception when readystate is another value.

The method of XHR

Method Description
Abort () Causes the currently executing request to be canceled
getAllResponseHeaders () Returns a single character | String containing the names and values of all the response headers
getResponseHeader (name) Returns the name and value specified in the response header
Open (METHOD,URL,ASYNC,USERNAME,PWD) Sets the HTTP method (get or post), and so on
Send (content) Issue a request with the specified body content
setRequestHeader (Name,value) Sets the request header with the specified name and value

Copy Code code as follows:

<script type= "Text/javascript" >
var oajax =oajax ();
alert (oajax.readystate);//eject "0"
Oajax.open ("Get", "index.html", true);
alert (oajax.readystate);//eject "1"
Oajax.send (NULL);
alert (oajax.readystate);//ie pops up 4, and Firefox is 2.
can be monitored by ReadyStateChange event
Oajax = XHR ();
Oajax.onreadystatechange = function () {
alert (oajax.readystate);//firefox is 1,2,3,4 in turn, but in the end there's going to be another 1.
IE is the 1,1,3,4
};
Oajax.open ("Get", "Index.txt", true);
Oajax.send (NULL);
</script>

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.