2013-10-29 83 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; 

希望这有助于。

相关问题