ajax stalled,Stalled and pending ajax requests by JQuery in Chrome

You can try this.

NOW UPDATED WITH ACTUAL WORKING CODE

(used some timezone code of my own so excuse the references to timezone)

First initialize arrays and run your request counting logic

var request = ( typeof request != 'undefined' && request instanceof Array ) ? request : [];

var pendingAjax = ( typeof pendingAjax != 'undefined' && pendingAjax instanceof Array ) ? pendingAjax : [];

Use .ajaxStart and .ajaxStop to keep track of the active requests.

var ajaxActive = 0;

$( document ).ajaxStart(function() {

ajaxActive++;

document.ajaxQueueFull = ajaxActive > 5;

});

$(document).ajaxStop(function() {

ajaxActive--;

document.ajaxQueueFull = ajaxActive > 5;

}

Create a function to build new requests

function ajaxRequestNew(t, u, d, s) {

var instance = request.length + 1;

request[instance] = $.ajax({

method: t,

url: u,

data: {ajaxPost: d },

success: s

});

return instance;

}

Now create your request getting the instance number returned

var instance = ajaxRequestNew('POST',

'js/ajax_timezone.php',

{ ajaxAction : "ajaxGetTimezone",

tzoffset : "0",

tztimezone: "America/New_York" },

function(data) { }

);

The $.ajax() function returns a XMLHttpRequest object. So we use a while loop to check when our ajax actually gets sent and aborts other active requests if the request is stalled.

while(request[instance] === null || (request[instance].readyState < 1 || request[instance].readyState > 4)) {

if (document.ajaxQueueFull) {

//abort existing requests

$.each(request, function(i,v) {

if (i !== instance) {

request[i].abort();

}

});

}

}

Push your request onto the stack

pendingAjax.push(request[instance]);

Create callbacks for your request

var timezoneFailCallback = function(data) {

console.log('fail');

console.dir(data);

};

var timezoneSuccessCallback = function(data) {

console.log('success');

console.dir(data);

};

use when to apply the callbacks

$.when.apply($, pendingAjax).done( timezoneSuccessCallback ).fail( timezoneFailCallback);

The code may need a little tweaking for your app, but hopefully you get the idea. Let me know if you have any questions.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值