Gun*_*Foo 70 ajax jquery long-polling
我正在使用.ajaxStart()和.ajaxStop()在发出ajax请求时显示模态.(开始和停止之间)
现在我想添加一个等待通知的longpoll函数,类似于本网站左上角的那个.
我现在的问题在于仅为longpolling请求禁用此模式.
注册"加载屏幕"打开和关闭处理程序:
$(document).ajaxStart(handleAjaxStart);
$(document).ajaxStop(handleAjaxStop);
Run Code Online (Sandbox Code Playgroud)
我的longpoll功能:
$.ajax({
timeout: 35000,
url: longPollUrl,
success: function(data){
if(data.queCount) $('#numQueCount').html(data.queCount);
if(data.queAccept) $('#numQueAccept').html(data.queAccept);
},
dataType: 'json',
complete: longpoll
});
Run Code Online (Sandbox Code Playgroud)
我试过了:
$().off('ajaxStart');
$().off('ajaxStop');
Run Code Online (Sandbox Code Playgroud)
..开始投票后重新连接处理程序,但没有快乐.
我也尝试将一个全局变量引入到handleAjaxStart()
该函数的第一行返回,但这似乎完全杀死了加载屏幕.
任何想法如何实现这一目标?
Gun*_*Foo 178
我想到了..
.ajax()
调用options对象中有一个属性global
.
如果设置为false,则不会触发ajaxStart
调用事件.
$.ajax({
timeout: 35000,
url: longPollUrl,
success: function(data){
if(data.queCount) $('#numQueCount').html(data.queCount);
if(data.queAccept) $('#numQueAccept').html(data.queAccept);
},
global: false, // this makes sure ajaxStart is not triggered
dataType: 'json',
complete: longpoll
});
Run Code Online (Sandbox Code Playgroud)
ahm*_*met 11
阅读完所有可能的解决方案后,我想结合答案.
//binding
$(document).bind("ajaxStart.mine", function() {
$('#ajaxProgress').show();
});
$(document).bind("ajaxStop.mine", function() {
$('#ajaxProgress').hide();
});
//Unbinding
$(document).unbind(".mine");
Run Code Online (Sandbox Code Playgroud)
这是一个折旧的解决方案.在jQuery 1.9之前,像ajaxStart,ajaxStop,ajaxError等ajax的全局事件可以绑定到任何元素.在jQuery 1.9之后:
从jQuery 1.9开始,jQuery全局Ajax事件的所有处理程序,包括那些添加了.ajaxStart()方法的处理程序,都必须附加到document.
因此,我们无法将这些事件绑定/解除绑定到自定义命名空间.
global
为false
$.ajax({
url: "google.com",
type: "GET",
dataType: "json",
global: false, //This is the key property.
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
Run Code Online (Sandbox Code Playgroud)
此解决方案可用于禁用ajaxStart()/ajaxStop()
事件.但是,它也会使禁用ajaxComplete(), ajaxError(), ajaxSend(), ajaxSuccess()
.如果您不使用这些全局事件,它似乎没问题,但是当需要时,您必须返回并更改您设置的所有页面的解决方案global: false
.
var showLoadingEnabled = true;
$(document).ready(function () {
$('#loading')
.hide() // at first, just hide it
.ajaxStart(function () {
if (showLoadingEnabled) {
$(this).show();
}
})
.ajaxStop(function () {
if (showLoadingEnabled) {
$(this).hide();
}
});
});
function justAnotherFunction() {
window.showLoadingEnabled = false;
$.ajax({
url: 'www.google.com',
type: 'GET',
complete: function (data) {
window.showLoadingEnabled = true;
console.log(data);
}
});
}
Run Code Online (Sandbox Code Playgroud)
不应在javascript文件中使用全局变量.但是,这是最简单的解决方案,我可以找到.
我首选的是我项目的第三个解决方案.