2017-08-18 79 views
-1

當我點擊Sort By Date Created按鈕,該字符串date被傳遞給函數sort()和警報1(見代碼)打印字符串date。 字符串date存儲在第一個if語句的會話中,並且警報2打印date。問題是date只是暫時存儲,並且警報3總是提示service,無論類型如何。如果我更改if語句的順序,最後的if語句的字符串總是以某種方式存儲在會話中。該會議將數據存儲第二被改變的最後一個會議前的值

<?php session_start(); ?> 
<html> 
<head> 
    <script> 

    function sort(type){ 

    alert('<?php echo $_SESSION['sort']; ?>'); ///ALERT 1 

    if (type == 'date'){ 
     <?php $_SESSION['sort'] = 'date'; ?> 
     alert('<?php echo $_SESSION['sort']; ?>'); ///ALERT 2 
    } 
    else if (type == 'cost'){ 
     <?php $_SESSION['sort'] = 'cost'; ?> 
     alert('<?php echo $_SESSION['sort']; ?>'); 
    } 
    else if (type == 'service'){ 
     <?php $_SESSION['sort'] = 'service'; ?> 
     alert('<?php echo $_SESSION['sort']; ?>'); 
    } 

    alert('<?php echo $_SESSION['sort']; ?>'); ///ALERT 3 
    } 

</script> 
</head> 
<body> 
    <input type="button" onclick="sort('date');" value="Sort By Date Created"> 
    <input type="button" onclick="sort('cost');" value="Sort By Cost"> 
    <input type="button" onclick="sort('service');" value="Sort By Service"> 
</body> 
</html> 

回答

0

您對客戶端和服務器端代碼之間的區別感到困惑。你已經基本上寫下面的代碼:

alert('service'); 
<?php 
    $_SESSION['sort'] = 'date'; 
    $_SESSION['sort'] = 'cost'; 
    $_SESSION['sort'] = 'service'; 
?> 
if (type == 'date'){ 

    alert('service'); ///ALERT 2 
} 
else if (type == 'cost'){ 

    alert('service'); 
} 
else if (type == 'service'){ 

    alert('service'); 
} 

PHP不尊重你的JavaScript if語句。 PHP將會編譯成一個靜態網頁,這是我寫的代碼的後半部分。

我覺得一個答案,試圖解釋客戶端和服務器端代碼之間的差異是有點寬泛和冗長的StackOverflow,但有很多資源在那個主題上。

+0

謝謝你的幫助。我會嘗試使用GET將數據傳遞到另一個頁面並將其存儲在:) – Demi