把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'];
从我所看到的,它好像你正试图从各种来源复制粘贴代码。我建议坐下来学习正确编程。 –
记住SESSION存在于服务器上,PHP也一样。但Javascript运行在浏览器上。 – RiggsFolly
不是@Raahim。我试图在一个页面的会话变量中存储一个值,并在另一个页面上访问它。以上是我为了解会话变量的工作而编写的简单代码。我不明白为什么上面的代码不起作用。第一页每隔几分钟更新会话变量的值。第二页不显示更新的值,除非页面被刷新,我不想刷新页面。任何帮助表示赞赏。谢谢。 –