简体   繁体   English

JS:遍历URL数组,并在出现任何错误时发出警报

[英]JS: loop through array of URL's and alert if any throw an error

I have an associative array of URL's, each with a unique identifier that i want to iterate through and whichever URL throws a 401 i'd like to set an alert of that specific url's identifier. 我有一个URL的关联数组,每个数组都有一个我要迭代的唯一标识符,并且无论哪个URL抛出401,我都希望为该特定URL的标识符设置警报。 I'm stuck at the alerting portion: 我被困在警报部分:

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

Use a closure: 使用闭包:

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

As described in the docs , the function that you associate with 401 can take the same arguments that the error callback. docs中所述,您与401关联的函数可以采用与error回调相同的参数。 Thus, you can write: 因此,您可以编写:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM