如果半小时没有活动,我希望我的用户自动退出网站。 (您在下面看到的代码设置为70秒而非1/2小时)。 我意识到我需要的是使用jQuery …这对于加载我的php脚本我是极其新的。 (我一直在研究这个问题太久了)这是我到目前为止所做的。
这是我的页面的头部。
var log_me_out = true; setTimeout(function(){ $.post({ url: "check_time.php", //data: optional, the data you send with your php-script success:function(){ if(log_me_out == 'yes'){ window.location = 'index_test.php'; } } }) }, 80000);
这是我的check_time.php页面
var log_me_out = true; log_me_out = 'yes'; log_me_out = 'no';
嗯,这看起来不错,但我建议稍微简化一下。 最好的方法是使用setTimeout函数中的代码,并在其中检查用户上次活动的时间。 所以设置一个像’lastActive’这样的变量,并使用类似的东西:
$(document).click(function(){ var currentTime = new Date(); lastActive = currentTime.getSeconds(); });
然后在你的setTimeout函数中你做了类似的事情:
var currentTime = new Date(); if(lastActive + 5000 < currentTime.getSeconds()){ //If user hasn't been active for 5 seconds... //AJAX call to PHP script }else { setTimeout(theSameFunction(),5000); }
然后在您的PHP中简单地销毁会话,然后成功回调函数应该只具有:
window.location = 'index_test.php';
在途中发送用户。
你在php文件中写的javascript将不会被执行。 要知道您的PHP脚本的function,请使用该代码:
Javascript:
$.post('check_time.php', function(data) { if(data == 'yes') { window.location = 'index_test.php'; } });
Php:
session_start(); if($_SESSION['admin_login'] != $password) { session_unset(); session_destroy(); echo 'yes'; } else { echo 'no'; }
您的代码需要返回可解析的内容,例如JSON,XML或HTML。 例如,更改check_time.php
以输出:
"true"); }else{ json_encode(array("log_me_out"=>"false"); } ?>
编辑HTML以包含这行JQuery代码:
setTimeout(function(){ $.post("check_time.php", function(d){ if(d.log_me_out){ window.location = 'index_test.php'; } }); }, 80000);
这里解决的问题是最终的工作代码
主页上的代码:
ini_set('session.gc_maxlifetime',1800); ini_set('session.gc_probability',1); ini_set('session.gc_divisor',1); session_start(); if($_SESSION['admin_login'] != $password){ header('Location: index.php'); exit(); } if(isset($_SESSION['last_activity']) && (time()-$_SESSION['last_activity'] >1800)){ // last request was more than 30 minates ago session_destroy(); // destroy session data in storage session_unset(); // unset $_SESSION variable for the runtime header('Location: index.php'); exit(); } $_SESSION['last_activity'] = time(); // update last activity time stamp ?> Here is the code on the check_time.php page 1800){ session_unset(); session_destroy(); echo "LOGOUT"; } }else{ echo "LOGOUT"; } ?>
以上就是jQuery教程分享使用jQuery调用php注销脚本相关内容,想了解更多jQuery开发(异常处理)及jQuery教程关注计算机技术网(www.ctvol.com)!)。
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/jquerytutorial/558795.html