javascript 如何在onbeforeunload上执行ajax函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9701734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to execute ajax function onbeforeunload?
提问by matheusvmbruno
I'm developing a php/javascript chat.
我正在开发一个 php/javascript 聊天。
When the user logs in, his/her username is inserted in a MySQL table called queue
.
This insert returns the mysql_insert_id()
that will be stored in a session variable called $_SESSION['CHAT_QUEUE_ID']
当用户登录时,他/她的用户名被插入到名为 的 MySQL 表中queue
。此插入返回mysql_insert_id()
将存储在名为$_SESSION['CHAT_QUEUE_ID']
I need the MySQL table row to be deleted when the user closes the page.
我需要在用户关闭页面时删除 MySQL 表行。
I tried the following, but without success:
我尝试了以下方法,但没有成功:
js file
js文件
window.onbeforeunload = closeSession;
function closeSession(){
$.ajax({
url: "/chat/process/chat.php",
type: "GET"
});
return "disconnected";
}
chat.php
聊天.php
$delete= "DELETE FROM queue WHERE id = " . $_SESSION['CHAT_QUEUE_ID'];
// query, etc
Is there any way to do this?
有没有办法做到这一点?
回答by StilgarBF
You fire your ajax async (default for jquery - ajax). But the browser won't wait for anything on unload.
您触发 ajax 异步(jquery 的默认设置 - ajax)。但是浏览器不会等待任何卸载。
try setting async : false
in the ajax-settings. But you can never be sure that this will work in all browsers everytime.
尝试async : false
在 ajax-settings 中设置。但是您永远无法确定这每次都适用于所有浏览器。
see the comment here: http://api.jquery.com/unload/#dsq-comment-body-132164390
请参阅此处的评论:http: //api.jquery.com/unload/#dsq-comment-body-132164390