ajax 事件排序,对ajax请求进行排序

jQuery 1.5+/*

* jQuery.ajaxQueue - A queue for ajax requests

*

* (c) 2011 Corey Frang

* Dual licensed under the MIT and GPL licenses.

*

* Requires jQuery 1.5+

*/ (function($) {// jQuery on an empty object, we are going to use this as our Queuevar ajaxQueue = $({});$.ajaxQueue = function( ajaxOpts ) {

var jqXHR,

dfd = $.Deferred(),

promise = dfd.promise();

// queue our ajax request

ajaxQueue.queue( doRequest );

// add the abort method

promise.abort = function( statusText ) {

// proxy abort to the jqXHR if it is active

if ( jqXHR ) {

return jqXHR.abort( statusText );

}

// if there wasn't already a jqXHR we need to remove from queue

var queue = ajaxQueue.queue(),

index = $.inArray( doRequest, queue );

if ( index > -1 ) {

queue.splice( index, 1 );

}

// and then reject the deferred

dfd.rejectWith( ajaxOpts.context || ajaxOpts,

[ promise, statusText, "" ] );

return promise;

};

// run the actual query

function doRequest( next ) {

jqXHR = $.ajax( ajaxOpts )

.done( dfd.resolve )

.fail( dfd.reject )

.then( next, next );

}

return promise;};})(jQuery);

jQuery 1.4

如果您正在使用jQuery 1.4,则可以利用空对象上的动画队列为您的元素的ajax请求创建自己的“队列”。

您甚至可以将其纳入您自己的$.ajax()替代品中。这个插件$.ajaxQueue()使用jQuery的标准'fx'队列,如果队列尚未运行,它将自动启动第一个添加的元素。(function($) {

// jQuery on an empty object, we are going to use this as our Queue

var ajaxQueue = $({});

$.ajaxQueue = function(ajaxOpts) {

// hold the original complete function

var oldComplete = ajaxOpts.complete;

// queue our ajax request

ajaxQueue.queue(function(next) {

// create a complete callback to fire the next event in the queue

ajaxOpts.complete = function() {

// fire the original complete if it was there

if (oldComplete) oldComplete.apply(this, arguments);

next(); // run the next query in the queue

};

// run the query

$.ajax(ajaxOpts);

});

};})(jQuery);

示例用法

所以,我们有

  • 一些
  • 我们想要复制(使用ajax!)的
    • // get each item we want to copy$("#items li").each(function(idx) {

    // queue up an ajax request

    $.ajaxQueue({

    url: '/echo/html/',

    data: {html : "["+idx+"] "+$(this).html()},

    type: 'POST',

    success: function(data) {

    // Write to #output

    $("#output").append($("

  • ", { html: data }));

    }

    });});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值