使用 jQuery / JS 创建 PHP 会话


Creating a PHP Session using jQuery / JS

在页面加载时,我想检查是否存在PHP会话变量:

  • 如果是,请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_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"); ?>