如何在onbeforeunload上执行ajax函数? [英] How to execute ajax function onbeforeunload?
问题描述
我正在开发一个php / javascript聊天。
I'm developing a php/javascript chat.
当用户登录时,他/她的用户名被插入名为队列
。
此插入返回 mysql_insert_id()
,它将存储在名为 $ _ SESSION ['CHAT_QUEUE_ID'] $ c的会话变量中$ c>
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表格行。
I need the MySQL table row to be deleted when the user closes the page.
I尝试了以下,但没有成功:
I tried the following, but without success:
js file
window.onbeforeunload = closeSession;
function closeSession(){
$.ajax({
url: "/chat/process/chat.php",
type: "GET"
});
return "disconnected";
}
chat.php
$delete= "DELETE FROM queue WHERE id = " . $_SESSION['CHAT_QUEUE_ID'];
// query, etc
有没有办法做到这一点?
Is there any way to do this?
推荐答案
你激活你的ajax异步(jquery - ajax的默认值)。但浏览器不会等待卸载任何内容。
You fire your ajax async (default for jquery - ajax). But the browser won't wait for anything on unload.
尝试在ajax-settings中设置 async:false
。但是你永远无法确定每次都能在所有浏览器中使用它。
try setting async : false
in the ajax-settings. But you can never be sure that this will work in all browsers everytime.
在这里看到评论:
http://api.jquery.com/unload/#dsq-comment-body-132164390
这篇关于如何在onbeforeunload上执行ajax函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!