使用 jQuery.queue() 排队 ajax 请求 [英] Queue ajax requests using jQuery.queue()
问题描述
我第一次使用 jQuery.queue() 并没有完全掌握它.有人可以指出我做错了什么吗?
I am using jQuery.queue() for the first time and haven't quite grasped it. Could someone please point out what I'm doing wrong?
查看萤火虫,我仍然看到我的 POST 请求同时触发 - 所以我想知道我是否在错误的地方调用了 dequeue().
Looking in firebug I am still seeing my POST requests firing at the same time - so I'm wondering if I'm calling dequeue() in the wrong place.
另外 - 我怎样才能得到队列长度?
Also - how can I get the queue length?
我需要对这些请求进行排队的原因是它会在单击按钮时被触发.并且用户可以快速连续点击多个按钮.
The reason I need to queue these requests is that it gets fired on click of a button. And its possible for the user to click multiple buttons in quick succession.
试图剥离我的代码的基本结构:
Tried to strip out the basic structure of my code:
$("a.button").click(function(){
$(this).doAjax(params);
});
// method
doAjax:function(params){
$(document).queue("myQueueName", function(){
$.ajax({
type: 'POST',
url: 'whatever.html',
params: params,
success: function(data){
doStuff;
$(document).dequeue("myQueueName");
}
});
});
}
推荐答案
你的问题是,.ajax()
触发异步运行的 Ajax 请求.这意味着, .ajax()
立即返回,非阻塞.因此,您将函数排队,但它们几乎会像您描述的那样同时触发.
You problem here is, that .ajax()
fires an asyncronous running Ajax request. That means, .ajax()
returns immediately, non-blocking. So your queue the functions but they will fire almost at the same time like you described.
我不认为 .queue()
是一个放置 ajax 请求的好地方,它更适合用于 fx 方法
.您需要一个简单的经理.
I don't think the .queue()
is a good place to have ajax requests in, it's more intended for the use of fx methods
. You need a simple manager.
var ajaxManager = (function() {
var requests = [];
return {
addReq: function(opt) {
requests.push(opt);
},
removeReq: function(opt) {
if( $.inArray(opt, requests) > -1 )
requests.splice($.inArray(opt, requests), 1);
},
run: function() {
var self = this,
oriSuc;
if( requests.length ) {
oriSuc = requests[0].complete;
requests[0].complete = function() {
if( typeof(oriSuc) === 'function' ) oriSuc();
requests.shift();
self.run.apply(self, []);
};
$.ajax(requests[0]);
} else {
self.tid = setTimeout(function() {
self.run.apply(self, []);
}, 1000);
}
},
stop: function() {
requests = [];
clearTimeout(this.tid);
}
};
}());
这离完美还很远,我只是想演示一下要走的路.上面的例子可以像
This is far away from being perfect, I just want to demonstrate the way to go. The above example could be used in a way like
$(function() {
ajaxManager.run();
$("a.button").click(function(){
ajaxManager.addReq({
type: 'POST',
url: 'whatever.html',
data: params,
success: function(data){
// do stuff
}
});
});
});
这篇关于使用 jQuery.queue() 排队 ajax 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!