2013-10-29 84 views
-1

嗨,我正在購物車中。我需要知道,當用戶更改選項時,即使在刷新頁面後,也應將新選項設置爲默認值。我該怎麼做?請幫助我如何在刷新頁面時保留下拉列表的選定值

+2

Cookie或會話變量 – Barmar

+0

也許有點迂迴,但本地存儲或存儲購物車服務器端也應該工作。 –

回答

2

當用戶選擇該選項時,嘗試將選項保存在cookie or a session by using a ajax call中。

因此,即使頁面被刷新,如果設置了cookie或會話變量,那麼您可以使用"selected"屬性將其設置爲默認值。

0

你只能用javascript來做。在這裏,我正在使用JavaScript的jQuery庫,最喜歡的。

* 邏輯

當用戶從下拉菜單中選擇您可以可以節省cokkie並在頁面加載時,你可以從cokkie檢索值和選項設置回的數據。

,並通過使用這個插件,你可以eaisly做到這一點

看到該插件:通過使用

if (jQuery.cookie('choosed')) { // checking if cokkie exist 
     $.removeCookie("test"); 
    } 

而且 https://github.com/carhartl/jquery-cookie

$(document).ready(function() { 

    if (jQuery.cookie('choosed')) { // checking if cokkie exist 
      $('<selector select>').val($.cookie("choosed")); // assiging value in select box 
     } 

}); 

的形式提交,您可以刪除的cookie onchange事件選擇你可以通過這樣做來設置。

$.cookie("choosed",$('<selector select>').val(); , { 
    expires : 10,   //expires in 10 days 

    path : '/',   //The value of the path attribute of the cookie 
         //(default: path of page that created the cookie). 

    domain : 'jquery.com', //The value of the domain attribute of the cookie 
         //(default: domain of page that created the cookie). 

    secure : true   //If set to true the secure attribute of the cookie 
         //will be set and the cookie transmission will 
         //require a secure protocol (defaults to false). 
}); 
+0

謝謝。是否有其他一些方法?由於我對cookie不熟悉 – user1991

+0

您將需要一個持久性存儲,這將在頁面刷新時保持您的數據。這隻能通過瀏覽器中的cookie完成。或者現在,在html5中的本地存儲可以做到這一點。或者你可以選擇會話,但是你必須在服務器端進行調用,通過** ajax **將該值存儲在會話變量中,方法是用戶選擇該選項。所以你可以反正這點。 – developerCK

0

你應該有一個自動保存,將在用ajax定期變量發送到服務器。 Donot將這些保存到數據庫中,但將它們保存在SESSION或cookie上。

下面是使用會話實現它的一種方法。

例子:

<form action="backend.php" method="post"> 
    Name : <input name="name" id="name_input" class="savable" value=<?php echo $_SESSION['save_name'];?>/> <br /> 
    Father's name : <input name="fathername" id="fathername_input" class="savable" value=<?php echo $_SESSION['save_fathername'];?>/> 
</form> 

您可能需要檢查是否設置了變量的value場。

腳本:

function autoSave(){ 
    $(".savable").each(function(){ 
     $.ajax("save.php",{id:this.id, value:this.val()}); 
    }); 
} 

上述功能,應定期使用setInterval()調用。

save.php:

$key = $_POST["id"]; 
$val = $_POST["value"]; 
$_SESSION["save_".$key] = $val; 

希望這有助於。

相關問題