簡體   English   中英

如果其他URL不可用,請從其他URL下載文件

[英]Download file from a different url if the others are not available

我有不同的URL指向不同的服務器,但有相同的文件,以確保上述服務器中的一個是活動的,我想嘗試從第一個服務器下載,如果失敗,請嘗試第二個服務器,依此類推。

如果有更好的方法來代替我使用的方法呢? 就是這樣的:

var urls=["http://Url1.com","http://Url2.com","http://Url3.com"]
    $.get(ulrs[0]).done(function () {
      alert("success");
    }).fail(function () {
       alert(" First failed!, try with second");
       $.get(ulrs[1]).done(function () {
         alert("success");
       }).fail(function () {
         alert("Second failed! Try with third...");
         $.get(ulrs[2]).done(function () {
           alert("success");
         }).fail(function () {
           alert("All failed!");
          });
       });
    });

編輯:我想將其概括化以便與具有不同大小的不同數組一起使用...

使用遞歸:

function requestNext(arr, success, error) {
    if (!arr.length)
        return error();

    function onError() {
        alert(url + " failed!");
        requestNext(arr, success, error);
    }
    var url = arr.shift();
    $.get(url).done(success).fail(onError);
}
var urls = ["http://Url1.com","http://Url2.com","http://Url3.com"];
requestNext(urls, function(){ alert("success"); }, function(){ alert("all failed") });

此功能完成后, urls數組將發生突變。 如果您不希望發生這種情況,請傳遞一個副本:

requestNext(urls.slice(), function(){ alert("success"); }, function(){ alert("all failed") });

或使用Dogbert的解決方案,更改var url = arr.shift(); 至:

var url = arr[0];
arr = arr.slice(1);

您可以使用一個簡單的遞歸函數:

function tryGet(urls, done, fail) {
  if (urls.length == 0) {
    fail();
  } else {
    $.get(urls[0])
      .done(done)
      .fail(function() {
        tryGet(urls.slice(1), done, fail);
      });
  }
}

演示:

tryGet(["http://Url1.com", "http://Url2.com", "http://Url3.com"], function(_, _, resp) {
  console.log(resp.status);
}, function() {
  console.log("all failed");
});

tryGet(["http://Url1.com", "http://Url2.com", "http://Url3.com", "/"], function(_, _, resp) {
  console.log(resp.status);
}, function() {
  console.log("all failed");
});

https://jsfiddle.net/Dogbert/t89xn9ej/

您的一般方法幾乎是唯一可用的方法。 一種或另一種方式是,您必須觸發多個請求,每個請求都在第一個請求之后,等待前一個請求完成后才被觸發。

您可以做的是使代碼更具可讀性,而不是全部嵌套,並使代碼動態化,從而可以處理N個URL。 就像是:

var urls = ['url-1', '/', 'url-2'/* etc */], next_index = 0;
function do_req() {
    $.get(urls[next_index]).done(success).error(function() {
        next_index++;
        if (urls[next_index]) do_req(); else alert('All URLs failed');
    });
}
function success() {
    alert('Address '+(next_index+1)+' ('+urls[next_index]+') worked!');
}
do_req();

您可以使用遞歸。 每當ajax請求失敗時,使用下一個網址進行另一個ajax調用,如下所示:-

var url = ["http://url1.com", "http://url2.com"]
var makeCall = function(url, index){
  var xhr = $.ajax(url[index])
  .done(function(data) {
    console.log("Got the data");
  })
  .fail(function() {
    console.log("Error : trying next url");
    makeCall(url, index+1);
  });
}
makeCall(url, 0);

正如主題頂部提到的,使用遞歸是一種很好的方法。

function loadFirst(query, successHandler, failHandler) {
    // Load next if any item in array exists
    if (Array.isArray(query) && query.length) {
        // Get next item and remove it from query
        $.get(query.splice(0, 1))
            // First successfull response
            .done(function (response) { successHandler(response); })
            // Go to the next iteration if request failed
            .fail(function() { loadFirst(query); });
    } else {
        // All requests failed
        failHandler();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM