jQuery中止请求

时间:2013-04-24 12:59:00

标签: jquery http abort

jQuery有一些中止API,可用于尝试中止请求。 jQuery实际上可以决定自己中止Ajax请求吗?

例如,假设飞行中有一堆Ajax请求,其中一个发生了奇怪的事情,jQuery决定中止所有其他请求。

这会发生吗?

1 个答案:

答案 0 :(得分: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
    }
}