- Creating an XMLHttpRequest object.
- Specifying and submitting your HTTP request to a web server.
- Synchronously or asynchronously retrieving the server’s response.
State Description
0: The request is not initialized.
1: The request has been set up.
2: The request has been sent.
3: The request is in process.
4: The request is completed.
readyState = 0 after you have created the XMLHttpRequest object, but before you have called the open() method.
readyState = 1 after you have called the open() method, but before you have called send().
readyState = 2 after you have called the send() method.
readyState = 3 after browser has established a communication with the server, but before the server has completed the response.
readyState = 4 after the request has been completed, and the response data have been completely received from the server.
The method parameter can have a value of “GET”, “POST”, or “HEAD”. Other HTTP methods, such as “PUT” and “DELETE” (primarily used in REST applications), may be possible.
The async parameter specifies whether the request should be handled asynchronously or not. “true” means that script processing carries on after the send() method, without waiting for a response, and “false” means that the script waits for a response before continuing script processing.
The send() method takes an optional parameter that may contain data of varying types. Typically, you use this to send data to the server using the POST method. You can explicitly invoke the send() method with null, which is the same as invoking it with no argument. For most other data types, set the Content-Type header using the setReuqestHeader() method before invoking the send() method. If the data parameter in the send(data) method is of type DOMString, encode the data as UTF-8. If data is of type Document, serialize the data using the encoding specified by data.xmlEncoding, if supported or UTF-8 otherwise.
function createHttpRequest() {
var httpRequest = null;
if (window.ActiveXObject) // For IE6 and below
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
else // For IE7 and Modern Browsers
httpRequest = new XMLHttpRequest();
return httpRequest;
}
XMLHttpRequest.open("GET", url, true);
If you pass false as the third argument to open(), the send() method is synchronous: it blocks and does not return until the server’s response has arrived. Asynchronous responses are generally preferred.
HTTP GET
var xmlHttpRequest = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
xmlHttpRequest.onreadystatechange = function() {
}
xmlHttpRequest.open("GET", "query.php?username=vivian", false);
xmlHttpRequest.send(null);
HTTP POST
var xmlHttpRequest = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
xmlHttpRequest.onreadystatechange = function() {
}
xmlHttpRequest.open("POST", "query.php", false);
xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttpRequest.send("username=vivian");
With POST requests, data is passed to the server in the body of the request, rather than encoding it into the URL itself. Since request parameters are encoded into the URL of a GET request, the GET method is suitable only when the request has no side effects on the server — that is, when repeated GET requests for the same URL with the same parameters can be expected to return the same result. When there are side effects to a request (such as when the server stores some of the parameters in a database), a POST request should be used instead.
Escape the Data
var HTTPUTILITY = {
encodeFormData: function(data) {
if (!data) return;
var pairs = [];
var regexp = /%20/g; // A regular expression to match an encoded space.
for (var name in data) {
// Create a name/value pair, but encode name and value first. The global function encodeURIComponent does almost what we want,
// but it encodes spaces as %20 instead of as "+". We have to fix that with String.replace().
var value = data[name].toString();
var pair = encodeURIComponent(name).replace(regexp, "+") + "=" + encodeURIComponent(value).replace(regexp, "+");
pairs.push(pair);
}
return pairs.join("&"); // Concatenate all the name/value pairs, separating them with &.
}
};
The POST method uses the AJAX.encodeFormData() function to convert the properties of an object to a string form that can be used as the body of a POST request. This string is then passed to the XMLHttpRequest.send() method and becomes the body of the request. (The string returned by AJAX.encodeFormData() can also be appended to a GET URL; just use a quest-mark character to separate the URL from the data.)
var xmlHttpRequest = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
xmlHttpRequest.onreadystatechange = function() {
if (xmlHttpRequest.readyState != 4) {
// Start to progress
} else { // The server's response is complete.
if (xmlHttpRequest.status == 0 || xmlHttpRequest.status == 200)
callback(xmlHttpRequest.responseText)
else
// Error
}
}
xmlHttpRequest.open("POST", "query.php", false);
xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttpRequest.send("username=vivian");
Notes on readyState 3
Data is being received from the server.readyState 3 differs somewhat in Firefox and Internet Explorer. Firefox invokes the onreadystatechange handler multiple times in readyState 3, to provide download progress feedback. A script might use these multiple invocations to display a progress indicator to the user. Internet Explorer, on the other hand, interprets the event handler name strictly, and invokes it only when the readyState value actualy changes. This means that it is invoked only once for readyState 3, no matter how large downloaded document is.
var timer = null;
var timeout = 1000;
var xmlHttpRequest = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
if (timeout) {
if (timer) clearTimeout(timer);
timer = setTimeout(function(){
xmlHttpRequest.abort();
}, timeout);
}
xmlHttpRequest.onreadystatechange = function() {
if (xmlHttpRequest.readyState != 4) {
// Start to progress
} else { // The server's response is complete.
if (timer) clearTimeout(timer);
if (xmlHttpRequest.status == 0 || xmlHttpRequest.status == 200)
callback(xmlHttpRequest.responseText)
else
// Error
}
}
xmlHttpRequest.open("POST", "query.php", false);
xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttpRequest.send("username=vivian");
By appending the julian day number to the end of the URL(?timestamp=123412341234), we effectively make each call unique and that means Internet Explorer will not cache the Ajax call as it is wont to do.
Leave a Reply
You must be logged in to post a comment.

