XMLHttpRequest connection return

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 the URL is ACTIVE or not? For example, does it try to enter that address, if it does not get it does it return an "Out of Site AR Alert"?

    
asked by anonymous 12.06.2014 / 16:27

2 answers

4

It's quite simple, just check the status property of the 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');
  }
};
    
12.06.2014 / 17:04
4

By active you mean if there was any response ?

If so, the correct way is to use timeout time.

The timeout property 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...'); }

Different status of 200 does not mean the site is down!

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

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

Even the error statuses ( 400 and 500 ) do not mean that the server is out of line. Being out of breath means not responding ; and to determine this we use the time called timeout .

    
13.06.2014 / 04:15