把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。我試圖在一個頁面的會話變量中存儲一個值,並在另一個頁面上訪問它。以上是我爲了解會話變量的工作而編寫的簡單代碼。我不明白爲什麼上面的代碼不起作用。第一頁每隔幾分鐘更新會話變量的值。第二頁不顯示更新的值,除非頁面被刷新,我不想刷新頁面。任何幫助表示讚賞。謝謝。 –