onbeforeunloadを使用して、Ajaxリクエストで変数をリセットします。ただし、実行されるのは1回だけです。たとえば、(ログイン後に)ページにアクセスしてウィンドウを閉じると、関数は実行されますが、操作を繰り返すと(ログインが完了した状態でブラウザにアドレスを入力してウィンドウを閉じる)、関数は実行されません。
window.onbeforeunload = function (e) {
//Ajax request to reset variable in database
resetDemoValueWithAjax();
};
//Ajax request to reset variable in database and exit
function resetDemoValueWithAjax(){
$.ajax({
async:true,
type: "POST",
dataType: "json",
url:"http://localhost/site/index.php/welcome/resetDemoValue",
data: {name: "demo"},
success:function(){
document.location.href='http://localhost/site/index.php/auth/logout';
},
error: function(){
document.location.href='http://localhost/site/index.php/auth/logout';
}
});
}
document.location.href='http://localhost/site/index.php/auth/logout';
別の瞬間にのみ使用されます:ユーザーがログアウトしたとき。ここではありません