问题
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