Return of Xmlhttprequest connection

Asked

Viewed 512 times

3

I have the following code:

function httpGet(theUrl)
{
    var xmlHttp = null;

    xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", theUrl, false );
    xmlHttp.send( null );
    return xmlHttp.responseText;
}
httpGet("www.xxxx.com.br/");

How do I test whether or not the URL is ACTIVE? For example, he tries to enter this address, if he can’t he returns me an Alert "Site off the AR"?

2 answers

4

For active you mean if there has been any response?

If yes, the correct way is using a time of timeout.

The estate timeout of the Xmlhttprequest object accepts a number in milliseconds of timeout, and the property ontimeout is the (function) call when this time is reached.

xmlHttp.timeout = 10000; //10 segundos
xmlHttp.ontimeout = function() { alert('Parece que o site está fora do ar...'); }

status other than 200 does not mean the site is out of breath!

All the 200 family of the HTTP protocol (201, 202, 203, 204...) have meant that the request was successful.

In addition to the redirect responses (family 300) can also be perfectly valid (for example status 304 is returned when the browser cache is used and not a new request).

Even the error status (400 and 500) do not mean that the server is down. Being out of the air means not answer; and to determine this we use the time called timeout.

4

It’s very simple, just check the property status AJAX request. For example:

var xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', url, false);
xmlHttp.send();

xmlHttp.onreadystatechange = function() {
  if ( xmlHttp.readyState === 4 && xmlHttp.status === 200 ) {
    // Continuação do código
  } else {
    alert('Fora do ar');
  }
};
  • Thanks @Júnior, I will test here and I already mark the answer.... any doubt I warn you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.