在页面加载时,我想检查 PHP Session变量是否存在:
>如果是,请提醒()内容
>如果没有,请创建它并保存当前时间
这是我的代码:
$(document).ready(function(){
<?php if(session_id() == '') { session_start(); } ?>
if (!<?php echo isset($_SESSION['lbBegin'])?'true':'false'; ?>) {
<?php $_SESSION['lbBegin'] = date("Y-m-d H:i:s"); ?>
} else {
alert("<?php echo $_SESSION['lbBegin']; ?>")
}
});
此代码的工作原理是第一页加载不会产生alert(),刷新会显示时间,但每次刷新/链接点击后都会更改时间.我期待在整个会议期间保持不变的时间.
我做错了什么?
最佳答案 您需要在开头添加session_start()并检查会话变量是否存在.这样做:
<?php session_start(); // At the very top! No matter what! ?>
<script>
$(document).ready(function(){
if (!<?php echo isset($_SESSION['lbBegin']) ? 'true' : 'false' ; ?>) {
// And you cannot do the below thing, because, first PHP executes before JS even runs. So, you need to use an AJAX Call for this:
<?php $_SESSION['lbBegin'] = date("Y-m-d H:i:s"); ?>
} else {
alert("<?php echo $_SESSION['lbBegin']; ?>")
}
});
</script>
更正AJAX位:
<?php session_start(); // At the very top! No matter what! ?>
<script>
$(document).ready(function(){
if (!<?php echo isset($_SESSION['lbBegin']) ? 'true' : 'false' ; ?>) {
// And you cannot do the below thing, because, first PHP executes before JS even runs. So, you need to use an AJAX Call for this:
$.getScript("setTime.php");
} else {
alert("<?php echo $_SESSION['lbBegin']; ?>")
}
});
</script>
在setTime.php里面添加代码:
<?php $_SESSION['lbBegin'] = date("Y-m-d H:i:s"); ?>