Ajax调用在onbeforeunload事件中不起作用 [英] Ajax call not working in onbeforeunload event
本文介绍了Ajax调用在onbeforeunload事件中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我具有一些功能,在使用浏览器的"X"按钮关闭浏览器之前,需要进行ajax调用以更新数据库值.我在关联文件的标题中使用了以下代码:
I have functionality in which I need to make a ajax call to update the database value before closing the browser using 'X' button of browser. I have used below code in the header of associated file:
$(document).ready(function() {
window.onbeforeunload = function(){
$.ajax('<?php echo base_url();?>index.php/ajax/myfunction?a=4');
}
});
在关闭浏览器时,该功能有效,但未执行ajax调用.
On closing the browser the function works but ajax call is not executed..
有什么解决方案?
推荐答案
以我的经验,也许不是最漂亮的代码,但是在超时线程中生成ajax调用就可以在整个浏览器中正常工作
Maybe not the prettiest code but spawning the ajax call in a timeout thread work well cross browser in my experience
$(window).bind("beforeunload", function (e) {
setTimeout(function(){
$.ajax({
type: 'GET',
async: false,
url: "[YOUR API CALL]"
});
}, 0);
});
请注意,我上次使用此功能是在使用jQuery 1.7的项目中
Note the last time i used this was on a project using Jquery 1.7
这篇关于Ajax调用在onbeforeunload事件中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文