在Ajax中优雅地处理404

时间:2014-03-20 07:01:30

标签: javascript ajax xmlhttprequest

我正在使用XmlHttpObject从服务器获取一堆文件。这些文件对我的应用程序并不重要,所以如果它们中的任何一个丢失,我只想记录错误并继续。问题是,无论何时找不到文件,都会引发异常,并且会破坏所有代码。

function loadFile(path) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.status == 404) {
            // I can live with that, log it and go on
            console.log("file missing");
            return;
        }

        if (xhr.readyState == 4) {
            // Wohoo, all is fine, do loading stuff
        }
    }

    xhr.open("GET", path, true);
    xhr.send();
}

// Some time after
for (var i in files) {
    loadFile(file[i]);
    // If a file is not found, an exception is raised and the code below doesnt execute
}
// More stuff

我该怎么做才能获得这种行为?

3 个答案:

答案 0 :(得分:1)

您的街区订购错误。仅在xhr.readyState更改为4时检查xhr.status。您正在过早地检查状态。

function loadFile(path) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if (xhr.status == 404) {
                // I can live with that, log it and go on
                console.log("file missing");
            }
            else {
                // Wohoo, all is fine, do loading stuff
            }
        }
    }

    xhr.open("GET", path, true);
    xhr.send();
}

// Some time after
for (var i in files) {
    loadFile(file[i]);
    // If a file is not found, an exception is raised and the code below doesnt execute
}
// More stuff

答案 1 :(得分:1)

您可能想要做的是传入一个应该在加载文件时调用的函数。正如Tys指出的那样,你应该在检查状态之前检查一下就绪状态:

function loadFile(path, onsuccess, onnotfound) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {

        if (xhr.readyState == 4) {
            if (xhr.status == 404) {
                // Do error handling when request is complete
                onnotfound(xhr);
                return;
            }
            // Wohoo, all is fine, do loading stuff
            onsuccess(xhr);
        }
    }

    xhr.open("GET", path, true);
    xhr.send();
}

// Some time after
for (var i in files) {
    loadFile(file[i], function(xhr) {
        // Stuff to process a successfull response  
        // Adding things to the DOM etc etc. based on the response
    },
    function(xhr) { 
        console.log("file missing");
        // Additional error handling on file missing
    });

}

答案 2 :(得分:0)

如果您正在使用Chrome进行编程,则解决此问题的唯一方法是在控制台中禁用此消息。根据{{​​3}}它的功能,而不是错误。去搞清楚。检查你是否在firefox中收到错误,如果没有,那么可能就是这个。