I'm learning XMLHttpRequest from w3schools. I don't understand the following snippet of code. What does window.XMLHttpRequest
signify? What makes it true or false? Is this entire if/else structure only there to account for ie6 and ie5, and if so can it all be replaced by one line which reads xmlhttp = new XMLHttpRequest()
?
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
Yes, i agree with harschware, having some cross-browser tool helps because it's a complex field.
The above code is a cross-browser code snippet that creates an XMLHTTPRequest
object.
It is well-structured because it relies on a functionality check rather than browser checking. See this article "Feature-Detect Rather Than Browser-Detect" at: http://www.javascripttoolbox.com/bestpractices/
So this:
if (window.XMLHttpRequest)
--detects whether the browser has XMLHttpRequest functionality implemented as a global function (members of window object), if so the XMLHttpRequest object is constructed that way.
Otherwise the code blindly assumes it can create the XMLHttpRequest by calling ActiveXObject functions, which is the way to create such an object in IE5 and IE6 as noted.
The last assumption might not be correct because the browser might not even have that functionality or it could be implemented in a different way. An exception could be raised on the last case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With