Should I continue to check if the XMLHttpRequest object exists?

I was a programmer, but now I do periodic "scripts". I am trying to create an Ajax based game.

I have a .php file with the following javascript:

if (window.XMLHttpRequest) {
 XMLHttpRequestObject = new XMLHttpRequest();
} else if ( window.ActiveXObject ) {
 XMLHttpRequestObject = new ActiveXObject("Microsoft.SML.HTTP");
}

Then, when I want to use the query, I have, for example:

if ( XMLHttpRequestObject ) {
 XMLHttpRequestObject.open("GET","gameinfo.php?cmd=setgame&game=" + arg);
 XMLHttpRequestObject.onreadystatechange = function() {
  // handler  ...
 }
 XMLHttpRequestObject.send(null);
}                

I don’t understand why I need to always be sure that the XMLHttpRequest object exists before I name it. Didn't I create it? How could this not exist? Is it just good coding practice, or is there any real risk?

OK, I am convinced that I am trying to execute jQuery. But if I stuck with pure javascript, would that be safe?

if (window.XMLHttpRequest) {
 XMLHttpRequestObject = new XMLHttpRequest();
} else if ( window.ActiveXObject ) {
 XMLHttpRequestObject = new ActiveXObject("Microsoft.SML.HTTP");
} else {
 alert("Sorry but it looks like this game won't work in your browser.");
}

Then, when I want to use the query, I have, for example:

XMLHttpRequestObject.open("GET","gameinfo.php?cmd=setgame&game=" + arg);
XMLHttpRequestObject.onreadystatechange = function() {
 // handler  ...
}
XMLHttpRequestObject.send(null);
+3
source share
4 answers

IFs, , , . , window.XMLHttpRequest IF window.ActiveXObject , . , .

, , , , : ", , - XMLHttpRequestObject, ".

? , , , , .

+1

: jQuery, .

, IE XMLHttpRequest - , , .

, ( if (window.XMLHttpRequest) {...) , .

, , jQuery. javascript. , , , -

$.get("gameinfo.php", 
    {cmd: "setgame", game: arg}, 
    function () { 
       //Success function
    }
);

-. ( jQuery , )

+1

, .

ajax, jquery js...

, . ajax- , raw javascript. jQuery... , .

0

How do you want him to catch up with him if he exists? Are you sure that it will be created 100%? Checked all browsers? Checked all the features?

0
source

Source: https://habr.com/ru/post/1790257/


All Articles