正在进行Ajax请求的jQuery

有没有办法检查是否有正在进行的ajax请求? 就像是:

if ( $.ajax.inProgress ){ do this; } else { do that; } 

您基本上应该在脚本设置为false基础上设置一个变量,并在ajax init上将其设置为true并在success处理程序中将其再次设置为false ,如此处所述

就在这里

$.ajax({ type: 'get', url: 'url', data: { email: $email.val() }, dataType: 'text', success: function(data) { if(data == '1') { $response.attr('style', '') .attr('style', "color:red;") .html('Email already registered please enter a different email.'); } else { $response.attr('style', '') .attr('style', "color:green;") .html('Available'); } }, beforeSend: function(){ $email.addClass('show_loading_in_right') }, complete: function(){ $email.removeClass('show_loading_in_right') } });
$.ajax({ type: 'get', url: 'url', data: { email: $email.val() }, dataType: 'text', success: function(data) { if(data == '1') { $response.attr('style', '') .attr('style', "color:red;") .html('Email already registered please enter a different email.'); } else { $response.attr('style', '') .attr('style', "color:green;") .html('Available'); } }, beforeSend: function(){ $email.addClass('show_loading_in_right') }, complete: function(){ $email.removeClass('show_loading_in_right') } }); 

当ajax请求刚刚启动时, beforeSend将执行您需要执行的过程,并且当ajax请求完成时将调用complete。
文件

要中止ajax请求,请使用

 if($.active > 0){ ajx.abort();//where ajx is ajax variable } 

要继续运行ajax请求,请使用

 if($.active > 0){ return; } 

你可能会喜欢这个:

 $(document).ready(function() { var working = false; $("#contentLoading").ajaxSend(function(r, s) { $(this).show(); $("#ready").hide(); working = true; }); $("#contentLoading").ajaxStop(function(r, s) { $(this).hide(); $("#ready").show(); working = false; }); $('#form').submit(function() { if (working) return; $.post('/some/url', $(this).serialize(), function(data){ alert(data); }); }); }); 

如果您完全控制javascript代码,则可以在每次启动ajax请求时递增变量,并在请求完成时递减它(成功,失败或超时)。 这样,您始终可以知道是否有正在进行的请求。