2015-12-12 95 views
-2

以下是一个示例PHP代码。我希望会话变量't'在更新函数被调用时递增其值。但是,当我运行代码时,我始终将输出作为值:1.我应该怎么做才能将值存储到会话变量中?在PHP中,会话变量不存储该值。哪里不对?

<?php 
session_start();  
if(!isset($_SESSION['t'])) { 
    $_SESSION['t'] = 0; 
} 
?> 
<div id="test" class="test"></div> 

<script src="http://code.jquery.com/jquery.js"></script> 

<script> 
    function update() { 

     var ct = "<?php echo $_SESSION['t'] += 1 ?>"; 

     <?php echo "Value: " . $_SESSION['t']; ?>; 

     $("#test").html(ct); 
    } 

    $(document).ready(function() { 
     setInterval('update()', 1000); 
    }); 
</script> 
+1

从我所看到的,它好像你正试图从各种来源复制粘贴代码。我建议坐下来学习正确编程。 –

+0

记住SESSION存在于服务器上,PHP也一样。但Javascript运行在浏览器上。 – RiggsFolly

+0

不是@Raahim。我试图在一个页面的会话变量中存储一个值,并在另一个页面上访问它。以上是我为了解会话变量的工作而编写的简单代码。我不明白为什么上面的代码不起作用。第一页每隔几分钟更新会话变量的值。第二页不显示更新的值,除非页面被刷新,我不想刷新页面。任何帮助表示赞赏。谢谢。 –

回答

0

session_start()在脚本的最顶端,任何输出

<?php 
    session_start(); 

    // if you automatically set SESSION['t'] to 0 when the page loads, it will never increment 
    // check if the SESSION exists, and if it doesn't, then we create it 
    if(!isset($_SESSION['t'])) { 
     $_SESSION['t'] = 0; 
    } 
?> 


<div id="test" class="test"></div> 

<!-- it's recommended to load scripts at the end of the page --> 
<script src="http://code.jquery.com/jquery.js"></script> 

<script> 
    function update() { 
     // you had some formatting issues in here... 

     // shortcut: using +=1 will take the current value of $_SESSION['t'] and add 1 
     var ct = "<?php echo $_SESSION['t'] += 1 ?>"; 

     <?php echo "Value: " . $_SESSION['t']; ?>; 

     $("#test").html(ct); 
    } 

    $(document).ready(function() { 
     setInterval('update()', 1000); 
    }); 
</script> 

更新前: 这是一个例子,将做你要找我想什么。当页面加载时,它将显示$_SESSION['t']的值,然后在每次单击更新按钮时递增$_SESSION['t']的值。没有错误检查,这只是一个非常简单的例子,向你展示这是如何工作的。

<?php 
    session_start(); 

    if(!isset($_SESSION['t'])) { 
     $_SESSION['t'] = 0; 
    } 
?> 


<div id="test" class="test"></div> 

<button type="button" id="update">Update</button> 


<script src="http://code.jquery.com/jquery.js"></script> 

<script> 
    $(document).ready(function() { 

     // create the ct varaible 
     var ct = <?php echo $_SESSION['t']; ?>; 

     // display the value in the #test div 
     $("#test").text(ct); 

     // when the update button is clicked, we call ajax.php 
     $("#update").click(function(){ 
      $.post("ajax.php", function(response){ 

       // display the returned value from ajax.php 
       $("#test").text(response); 
      }); 
     }); 

    }); 
</script> 

ajax.php

<?php 

session_start(); 

// increment the session by 1 
$_SESSION['t'] += 1; 

// return the result 
echo $_SESSION['t']; 
+0

谢谢!但是,除非页面刷新,否则该值不会更新。 –

+0

正确,这就是你的代码告诉它做的。你将需要编写一个函数或事件处理程序来执行更新'onclick',或其他... – timgavin

+0

为什么投票? – timgavin