ajax延迟显示,ajax延迟插件

这段代码展示了如何创建一个XHRService类,用于处理Ajax请求的延迟执行。通过设置reqDelay和loadingDelay,可以在请求前显示loading指示,并在请求完成后隐藏。在请求过程中,如果已有请求正在进行,则会取消之前的请求,确保只执行最新的请求。
摘要由CSDN通过智能技术生成

最近遇到需要做ajax延迟的需求,上一段代码记录下:

var XHRService = function(options) {

this.options = options;

this.reqTimer = null;

};

XHRService.prototype = {

constructor: XHRService,

req: function(options) {

var that = this,

defer = $.Deferred();

clearTimeout(this.reqTimer);

this.reqTimer = setTimeout(function() {

that._req(options, defer);

}, this.options.reqDelay);

return defer.promise();

},

_req: function(options, defer) {

var that = this;

if (this.xhr) {

this.xhr.abort();

}

if (typeof this.options.before === 'function') {

clearTimeout(this.loadingTimer);

this.loadingTimer = setTimeout(function() {

that.options.before();

}, this.options.loadingDelay);

}

this.xhr = $.ajax(options).done(function(data) {

defer.resolve(data);

})

.always(function(res, status, xhrObj) {

clearTimeout(that.loadingTimer);

if (typeof that.options.after === 'function') {

that.options.after();

}

if (xhrObj === that.xhr) {

that.xhr = null;

}

});

}

};

var xhr = new XHRService({

reqDelay: 10,

loadingDelay: 10,

before: function() {

console.log('show loading...');//显示loadingbar

},

after: function() {

console.log('hide loading...');//隐藏loadingbar

}

});

xhr.req({

url: url,

dataType: 'json'

}).done(function(data) {

console.log('done!');

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值