2009-11-08

AJAX Offline: referencing the window.location

The javascriptkit.com site makes some interesting points about AJAX and the implementation of the responseXML property of the XMLHttpRequest object.

"If you're running an Ajax request offline locally on your PC, a value of 0 is returned by status in most browsers regardless of the actual request status, even if it was successful. To run and test Ajax requests locally, it should overlook the status code being 200, and merely rely on a readyState value of 4. The following example takes into account the request possibly being run offline and to enable it:"

var myrequest = new ajaxRequest()
myrequest.onreadystatechange=function() {
  if ( myrequest.readyState == 4 ) { //if request has completed
    if ( myrequest.status == 200 || 
      window.location.href.indexOf("http") == -1 ) {

      /* if request was successful 
         (versus "page not found" etc) 
         or if run offline (rely on readyState of
         4 alone then) */

      // ... do something with returned data ...

  }
 }
}

From the example, it is clear that the test

window.location.href.indexOf("http") == -1

can be generally useful for other things - like finding the protocol string from the URL of the current document. In theory, at least, this should tell you what protocol was used to load the content of window.