簡體   English   中英

使用jQuery Deferred對象管理Ajax調用

[英]Managing ajax calls with jQuery Deferred object

我必須在給定的時間檢查設備中互聯網的可用性。 因此,我正在對服務器進行ajax調用以加載微小圖像。 我遇到了jQuery Deferred並嘗試使用它。

var spacer = "some url";
var getImage;
var connectionAlive;
function checkOnline(spacer) {
    getImage = $.ajax({url:spacer})
                .done(function() {console.log('Connection alive');connectionAlive = true;})
                .fail(function() {console.log('Connection dead');connectionAlive = false;});
    if(connectionAlive === true) {
        return true;
    }
    return false;
}

現在,當某些事件發生時,我必須調用此checkOnline函數。 因此,我正在調用該函數並等待直到諾言解決。

$(document).on('click','#explore',function() {
    checkOnline(spacer);
    getImage.done(function() {
            // Do something
            })
 });

這僅在第一次使用時有效,我認為這是因為延遲的對象狀態一旦解決就保持不變。 我應該如何編寫代碼,以便每次單擊事件觸發時都可以實際檢查連接?

新代碼:

嗨,我遵循了上面的代碼,但click事件僅在第一次正確運行。

    var connectionAlive;
var url = "http://example.com";
function checkOnline(url, callback1,callback2) {
    $.ajax({url:url})
        .done(function() {console.log('Connection alive');connectionAlive = true;})
        .done(callback1)
        .fail(function() {console.log('Connection dead');connectionAlive = false;})
        .fail(callback2);

}

$(document).on('click','#explore',function() {
    checkOnline(url, function(){
        console.log('Connection Alive from event');
    },function() {
        console.log('Connection Dead from event');
    });

});

更改checkOnline以返回承諾本身:

$(document).on('click','#explore',function() {
     checkOnline('url.com').done(function(){
          // Do something
     });
});

var connectionAlive;
function checkOnline(url) {
    return $.ajax({url : url})
            .done(function() {console.log('Connection alive');connectionAlive = true;})
            .fail(function() {console.log('Connection dead');connectionAlive = false;});
}

或更改它以進行回調:

$(document).on('click','#explore',function() {
     checkOnline('url.com', function(){
          // Do something
     });
});

var connectionAlive;
function checkOnline(url, callback) {
    $.ajax({ url : url})
     .done(function() {console.log('Connection alive');connectionAlive = true;})
     .done(callback)
     .fail(function() {console.log('Connection dead');connectionAlive = false;});
     // Do not try to return connectionAlive from here,
     // it will return the value before the ajax response arrived
}

暫無
暫無

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

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