无法保留 Ajax 个保留的会话变量

Cannot Keep Ajax Preserved Session Variables

我正在尝试编写代码以将会话变量从一个 php 带到另一个 php 而无需刷新。我尝试按照我在网上找到的示例进行操作,如下所示。加载ajax页面时好像成功带值了。但是,即使我使用 session_start() 命令,创建的会话变量似乎也无法保留。它没有加载数据,而是显示以下错误消息:

Notice: Undefined index: numSum in C:\xampp\htdocs\test\update.php on line 5

如果有人可以建议如何处理代码以使其正确,我将不胜感激。

index.php

<html>
<?php
    session_start();
?>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
    j_TOC = [1,2,3,4,5];

    $.ajax({
      method: "POST",
      url: "update.php",
      data: { numSum: j_TOC}
    })

      .done(function( msg ) {
        alert( "Data Saved: " + msg );
      });

 </script>
</html>

update.php

<html>
<?php
    session_start();
    session_save_path('/session_data/');
    $_SESSION['numSum1'] = $_POST['numSum'];

    ?>
<script type="text/javascript">
    function atest() {

        var id_toc = <?php echo json_encode($_SESSION['numSum1']); ?>;
        window.alert(id_toc);
    {

</script>
    <input type="button" id="clickme" onclick="atest()" value="update session"></>
</html>

session_save_path() 应在 session_start() 之前调用,如果您要使用它,请在使用 session_start()

的两个脚本中使用它

update.php 应该只是 return alert() 的字符串。当您直接加载该页面时,$_POST 是空的,这就是您看到的错误。

您的代码存在一些问题,例如:

  • 正常代码流程:第一次访问index.php时,会触发AJAX请求,并随后设置会话变量;这样当您访问 update.php 页面时,您就会得到想要的结果。
  • 你的代码流程: 说了以上几点,如果你直接访问update.php没有首先访问 index.php 的页面,你会得到这个错误,

    Notice: Undefined index: numSum in ...

    那是因为$_POST['numSum']没有设置,实际上整个超全局$_POST数组是空的。

    所以解决方案就是这样,

    将此语句 $_SESSION['numSum1'] = $_POST['numSum']; 包装在 if 块中,如下所示:

    if(!isset($_SESSION['numSum1']) || empty($_SESSION['numSum1'])){
        $_SESSION['numSum1'] = isset($_POST['numSum']) ? $_POST['numSum'] : array();
    }
    
  • 您的代码中还有一个小语法错误,

    function atest() {
    
        var id_toc = <?php echo json_encode($_SESSION['numSum1']); ?>;
        window.alert(id_toc);
    {   <============ See here, it should be }
    

    您忘记添加右括号}

  • 最后,来自the documentation

    ... Session data path. If specified, the path to which data is saved will be changed. session_save_path() needs to be called before session_start() for that purpose.

已编辑:

按以下方式更改您的 if 块,

if(!isset($_SESSION['numSum1']) || empty($_SESSION['numSum1']) || (isset($_POST['numSum']) && $_POST['numSum'] != $_SESSION['numSum1'])){
    $_SESSION['numSum1'] = isset($_POST['numSum']) ? $_POST['numSum'] : array();
}

此外,了解 PHP 中的比较运算符,尤其是三元运算符。您所说的问号(?:)与三元运算符有关。这里有必要的参考,