JS:循环遍历URL的数组,如果有任何错误则发出警报

时间:2013-02-04 21:35:00

标签: javascript jquery ajax loops

我有一个URL的关联数组,每个都有一个我想要迭代的唯一标识符,无论哪个URL抛出401我想设置该特定网址标识符的警报。我被困在警戒部分:

   for (var i=0; i<lyrs.length; i++){
        $.ajax({
            url: lyrs[i],
            dataType: 'json',
            statusCode: {
                401: function(){
                    console.log('there was a 401 error on something');
                }
            }
        });            
    }

2 个答案:

答案 0 :(得分:1)

使用闭包:

for (var i=0; i<lyrs.length; i++){
        (function() {
             var url=lyrs[i];
             $.ajax({
                 url: url,
                 dataType: 'json',
                 statusCode: {
                     401: function(){
                         console.log('there was a 401 error on '+url);
                     }
                 }
             });
        })();          
    }

答案 1 :(得分:0)

the docs中所述,您与401关联的函数可以采用与error回调相同的参数。因此,你可以写:

. . .
statusCode: {
    401: function(jqXHR, textStatus, errorThrown) {
        // alert with the specific details
    }
}