Cross-Browser XMLHttpRequest
Internet Explorer 6.0 has a different interface to XMLHttpRequest than Firefox, Safari, and Opera, though that will be fixed in Internet Explorer 7.0. Most of the cross-browser XMLHttpRequest snippets on the web are unnecessarily complex. This recipe works in IE 5.5+ and all recent versions of Firefox, Safari, and Opera:
function createXMLHttpRequest() {
if (typeof XMLHttpRequest != "undefined") {
return new XMLHttpRequest();
} else if (typeof ActiveXObject != "undefined") {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
throw new Error("XMLHttpRequest not supported");
}
}
If you run into other recipes on the web that look more complicated (like this one), note that there is no need to try any ActiveXObject arguments other than Microsoft.XMLHTTP, which does the "right thing" in IE 5.5+. See MSDN's discussion of the issue for more information.
Example usage:
var request = createXMLHttpRequest();
request.open("GET", "myfile.txt", true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
var node = document.createTextNode(request.responseText);
document.getElementById("output").appendChild(node);
}
}
request.send(null);





Comments
Its also worth noting that appending the text via a textnode will NOT render any tags you have in the resultant code.
So unless your fetching plain text then you will have to update the function.
request.open("GET", "myfile.txt", true);
can be replace to
request.open("GET", "myfile.txt");
<a href="http://www.jibbering.org/2002/4/httprequest.html">Jim Ley</a> has a good description of how the whole object, and lots of examples.
I scouted out for an article and found this one (I'm not pretending to have found the most accurate, merely one that describes the problem better than this comment):
http://www.techtoolblog.com/archives/ie-7-native-xmlhttprequest-not-so-good
Really Helpful for a newcomer like me...
var request = createXMLHttpRequest();
request.open("GET", "<testfilehere>", true);
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
var node = document.createTextNode(request.responseText);
document.getElementById("output").appendChild(node);
}
}
request.send(null)
Write a Comment