我正在使用blockUI jQuery插件进行AJAX调用:
//start the plugin
App.utilities.Loading();
$.ajax(url, {
type: "POST",
contentType: 'application/json',
data: JSON.stringify({
"textcontent": content
}),
success: function (data) {
$.mobile.navigate('discussion.html');
$.unblockUI();
}
});
有时加载时间超过三秒,如果用户按下后退按钮,则在调用$ .unblockUI()后会触发后退事件;有没有办法在插件启动期间返回并取消Ajax调用?
我可以获得块UI的状态:
var isUIBlocked = $('.ui-widget-overlay:visible').length > 0;
任何想法?
答案 0 :(得分:3)
您可以尝试以下代码
//start the plugin
App.utilities.Loading();
//assign the ajax call to a xhr object
var xhr = $.ajax(url, {
type: "POST",
contentType: 'application/json',
data: JSON.stringify({
"textcontent": content
}),
success: function (data) {
$.mobile.navigate('discussion.html');
$.unblockUI();
}
});
//when back button is being clicked
window.onbeforeunload = function (e) {
xhr.abort(); //abort the above ajax call
var isUIBlocked = $('.ui-widget-overlay:visible').length > 0;
if(isUIBlocked) {
$.unblockUI();
}
}
进一步阅读jquery.ajax函数的jqXHR对象:http://api.jquery.com/jQuery.ajax/#jqXHR