如何在刷新页面时保留下拉列表的选定值

时间:2013-10-29 08:45:13

标签: php

您好我正在购物车。我需要知道,当用户更改选项时,即使刷新页面后,新选项也应设置为默认值。我该怎么办?请帮帮我

3 个答案:

答案 0 :(得分:2)

当用户选择该选项时,请尝试将该选项保存在cookie or a session by using a ajax call

因此,即使刷新页面,如果设置了cookie或会话变量,也可以使用"selected"属性将其设置为默认值。

答案 1 :(得分:0)

您只能使用javascript执行此操作。在这里,我使用jquery库作为javascript,最喜欢。

*的逻辑

当用户从下拉列表中选择时,您可以将数据保存在cokkie中,在页面加载时,您可以从cokkie中检索值并将其设置在选项中。

并且通过使用此插件,您可以轻松地执行此操作

查看插件: 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
if (jQuery.cookie('choosed')) { // checking if cokkie exist
         $.removeCookie("test");
    }

选择 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).
});

答案 2 :(得分:0)

您应该有一个自动保存,它将使用ajax定期将变量发送到服务器。不要将这些保存到数据库中,但将它们保存在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;

希望这有帮助。