function getHTTPObject() {
var xmlhttp;
// branch for native XMLHttpRequest object
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
// branch for IE/Windows ActiveX version
else if (window.ActiveXObject){
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}else{
return false;
}
return xmlhttp;
}
var http = getHTTPObject(); // We create the HTTP Object
| Method | Description |
|---|---|
abort() | Stops the current request |
getResponseHeader("headerLabel") | Returns the string value of a single header label |
open("method", "URL"[, asyncFlag]) | Assigns destination URL, method, and other optional attributes of a pending request |
send(content) | Transmits the request, optionally with postable string or DOM object data |
setRequestHeader("label", "value") | Assigns a label/value pair to the header to be sent with a request |
Once a request has been sent, scripts can look to several properties that all implementations have in common, shown in Table 2. All properties are read-only.
| Property | Description |
|---|---|
onreadystatechange |
Event handler for an event that fires at every state change |
readyState |
Object status integer: 0 = uninitialized 1 = loading 2 = loaded 3 = interactive 4 = complete**** |
responseText |
String version of data returned from server process |
responseXML |
DOM-compatible document object of data returned from server process |
status |
Numeric code returned by server, such as 404 for "Not Found" or 200 for "OK" |
statusText |
String message accompanying the status code |
function handleHttpResponse() {
//first, is my 'object' complete (done getting info from server?)
if (http.readyState == 4) {
//if I got something...
if (http.status==200) {
// Use the XML DOM to unpack the data
var xmlDocument = http.responseText; // OR var xmlDocument = http.responseXML;
//finally, do something with the returned text or XML!
//...
}
}
}
//on a button click or some other event...
function addUser(who) {
//if I'm not currently looking something up and the object exists...
if (!isWorking && http) {
http.open("GET", URL, true);
http.onreadystatechange = handleHttpResponse;
isWorking = true;
http.send(null);
}
}