Code

Coding, Programming & Algorithms, Tips, Tweaks & Hacks
Search

Sponsored Ads

Loading AJAX locally, without a webserver

So far, while developing web applications I have always taken one point into assumption - that it has to run on a web-server. But when dealing with pure client-side web apps, we often overlook the fact that it should be able to be run by simply double-clicking on the homepage file (index.html). When XMLHttpRequest's readyState reaches a value of 4, we further check for a response code 200 from the web-server before doing anything with the responseText / responseXML. But when running it locally - not on a webserver, the status code value will alway be 0.
JavaScript
window.onload = function()
{
    var xhr = NewXMLHttpRequest();
    if (xhr != false)
    {
        try
        {
            xhr.open("GET", "local-ajax.txt", true);
            xhr.onreadystatechange = xhr_load;
            xhr.setRequestHeader("Connection", "close");
            xhr.send(null);
        }
        catch(e)
        {
            alert("Error Loading File\n" + e.code + "\n" + e.message);
        }
    }
    else
    {
        alert("AJAX not supported");
    }
}

function xhr_load()
{
    switch (this.readyState)
    {
        case 1: // Open
        case 2: // Send
        case 3: // Receiving
        break;

        case 4: // Loaded
        if (this.status == 200 || (this.status == 0 && document.location.protocol == "file:")) // OK
        {
            var text = this.responseText;
            alert(text);
        }
        break;
    }
}

function NewXMLHttpRequest()
{
    var xhr = false;

    if (window.XMLHttpRequest) // native XMLHttpRequest object
    {
        try { xhr = new XMLHttpRequest(); }
        catch(e) { xhr = false; }
    }
    else if (window.ActiveXObject) // IE/Windows ActiveX version
    {
        try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); }
        catch(e)
        {
            try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); }
            catch(e) { xhr = false; }
        }
    }

    return xhr;
}
JavaScript 1.5
Vanakkam !

0 comments: