AJAX:如果状态代码为200,请检查URLS

时间:2015-09-17 11:08:00

标签: jquery ajax

我正在尝试创建一个代码来检查URL列表(如果可用或不可用)但我的问题是它只返回循环内的最后一个链接。

下面是我的代码:

$('#dlink').click(function(e) {
    e.preventDefault();
    var dcode = $('#dnum').text();
    var dtemp = 0;
    for(dtemp = 1; dtemp <= 10; dtemp++) {
      var dlink = 'http://sample.com/export_template' + dtemp + '?field_delivery_code_value=' + dcode;
      $.ajax(
      {
        type: 'GET',
        cache: 'FALSE',
        url: dlink,
        success: function(response) {
          window.open(dlink);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
        console.debug("error for " + dtemp);
        console.log(XMLHttpRequest);
        }
      });
    }
});

2 个答案:

答案 0 :(得分:1)

这是一个可以帮助你做到这一点的功能,你不需要jQuery。

var is200 = function (url, callback) {
  var request = new XMLHttpRequest();
  request.open('GET', url, false)
  request.onreadystatechange = function () {
      // At ready state 2, headers are received and status code by extension
      if( request.readyState == 2)
        return callback(request.statusCode == 200);          
      }
  };
  request.open(null);
};

回调函数将有一个参数:状态代码与数字200相等的布尔值。

答案 1 :(得分:0)

在循环中使用回调并将变量传递给循环内部更新的变量。因此,当调用回调时,更新后的变量将使用最后一个状态进行所有回调! 有关详细信息,请参阅此主题:When using callbacks inside a loop in javascript, is there any way to save a variable that's updated in the loop for use in the callback?

相关问题