jQuery有一些中止API,可用于尝试中止请求.jQuery实际上是否可以决定中止Ajax请求?
例如,假设飞行中有一堆Ajax请求,其中一个发生了奇怪的事情,jQuery决定中止所有其他请求.
这会发生吗?
除了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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
539 次 |
| 最近记录: |