2015-12-12 132 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