Ajax call not working in onbeforeunload event [duplicate]

心已入冬 提交于 2020-01-25 10:29:09

问题


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');
     }
});

On closing the browser the function works but ajax call is not executed..

What's the solution?


回答1:


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);
});

Note the last time i used this was on a project using Jquery 1.7



来源:https://stackoverflow.com/questions/15271070/ajax-call-not-working-in-onbeforeunload-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!