Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain XMLHttpRequest creation

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");
 }
like image 235
temporary_user_name Avatar asked Apr 21 '12 01:04

temporary_user_name


1 Answers

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.

like image 113
neu-rah Avatar answered Nov 27 '22 02:11

neu-rah