Posts: 40
Name: Bob Davis
Location: Los Angeles, CA
|
Can someone help me out and take a look at my code snippet to see if it looks like a correct Object Request. I really appreciate any input. I want to have something CORRECT on hand to use when I need a starting point.
Code:
// basic variable setup
window.onload = createRequest; // runs the function when the page loads
var xhr = false; // makes sure xhr is false to begin
var url = "whatever.xml"; // this will be the link called in the open method later
// CREATE THE REQUEST
function createRequest () {
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { }
}
}
// provides the information needed to properly create the request
if (xhr) {
xhr.onreadystatechange = showContents; // references the function showContents (BELOW)
xhr.open("GET", url, true); // true is asynchronous
xhr.send(null);
}
else {
window.alert("Sorry, but I couldn't create an XMLHttpRequest"); // the request could not be created
}
}
// DISPLAY THE REQUESTED INFORMATION - once the request has been created
function showContents () {
if (xhr.readyState == 4) { // the request has finished loading
if (xhr.status == 200) { // the information is okay
var outMsg = xhr.responseText; // assigns a variable; this could be responseText OR responseXML
// if necessary, other code could be placed here that will eventually be used
}
else {
var outMsg = "There was a problem with the request " + xhr.status; // this is the error message
}
// Put code here to do something with outMsg
}
}
Last edited by chrishirst; 08-19-2010 at 03:25 PM..
|