在页面加载时,我想检查是否存在 PHP session 变量:
- 如果是,
alert()
内容 - 如果没有,则创建并保存当前时间
这是我的代码:
$(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 期间时间保持不变。
我做错了什么?
最佳答案
您需要在最开始添加session_start()
并检查是否存在 session 变量。这样做:
<?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"); ?>
关于javascript - 使用 jQuery/JS 创建 PHP session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34852983/