在Ajax中优雅地处理404

Gracefully handling 404 in Ajax

本文关键字:处理 Ajax      更新时间:2023-09-26

我使用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

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

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

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
    });
}

你的积木顺序不对。只检查xhr。状态时xhr。readyState已更改为4。您过早地检查了状态。

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

如果你在chrome中编程,唯一的方法是通过在控制台中禁用此消息来修复它。根据Chromium团队的说法,这是一个特性,而不是一个bug。图。检查火狐中是否出现错误,如果没有,可能是这样。