2013-04-24 51 views
3

jQuery有一些中止API,可用於嘗試中止請求。 jQuery實際上是否可以決定自己放棄一個Ajax請求?jQuery中止請求

例如,假設有一堆Ajax請求正在運行,並且有一些奇怪的東西從其中一個回來,使得jQuery決定中止所有其他請求。

這會發生嗎?

回答

5

除了timeout選項,通常jQuery不決定。 決定。

例行程序將始終有一個$.ajax()返回給你的參考。

含義,而不是僅僅調用$.ajax(),而不是xhr = $.ajax()

$.ajax()返回一個jqXHR對象,它只是Ajax功能的jQuery包裝器。見http://api.jquery.com/jQuery.ajax/

現在你有xhr,你可以從任何你想要的電話xhr.abort()

真的取決於你如何設計它,但進行.abort()調用。以下可能是一個可能的用例。

一個輪詢函數,以及另一個函數,用於檢查用戶是否閒置太久。

如果用戶空閒,請中止輪詢ajax,然後可能會提示一條警告用戶會話結束的消息。

實施例用例:

var mainXHR; // this is just one reference. 
      // You can of course have an array of references instead 

function mainPollingFunction() { 
    mainXHR = $.ajax({ 
     url: 'keepAlive.php', 
     // more parameters here 
     timeout: 10000, // 10 seconds 
     success: function() { 
      // server waits 10 seconds before responding 
      mainPollingFunction(); // initiate another poll again 
     } 
    }); 
} 

// Let's say this function checks if the user is idle 
// and runs when a setTimeout() is reached 
function otherFunction() { 
    if (/* if user is idle */) { 
     if (mainXHR) mainXHR.abort(); // abort the ajax in case it's still requesting 
    } 
}