在Cookie中存储用户首选项

时间:2015-06-24 21:11:09

标签: javascript php jquery cookies

我正在使用php创建一个网站,允许用户过滤通过复选框显示的内容。我想保存他们的偏好。我正在使用jquery.mmenu并生成如下复选框

<form id="menu-right method="post" action="">
<li>
<a href="">'. $sportArray[$ids]["Event"] . '</a>
<input type="checkbox" class="Toggle" name="sportList[]" value="'.$sportArray[$ids]["Event"].'" />
</li>'
</form>

我可以通过以下代码收集一个数组并打印数组的值,但是我无法设置cookie,检索cookie,甚至没有开始在复选框中添加一个检查来恢复加载复选框时'检查'值。我通过javascript和php尝试了很多方法,没有运气。我理解CSS中有伪元素打破了javascript的几个选项

<?
if(isset($_POST['sportList'])) { 
for ($i=0; $i<=count($_POST['sportList']); $i++){
    echo $_POST['sportList'][$i];
    setcookie('userSportList[$i]', $_POST['sportList'][$i], time()+60*60*24*365, '/');
} 
}
?>

任何解决方案都欢迎..在这个阶段可能是愚蠢的,因为我现在尝试了很多选择。诸如localstorage之类的替代品也值得欢迎,这是最好的解决方案

<?php
            if(isset($_POST['sportList'])) { 
                session_start();
                $_SESSION['sesUserPrefs'] = $_POST['sportList'];

                $serUserPrefs = serialize($_SESSION['sesUserPrefs']);
                $bcSerUserPrefs = base64_encode($serUserPrefs);

                $expire = 2000000000;
                setcookie("cUserPrefs", $bcSerUserPrefs, time()+$expire);

            }
?>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html;charset=iso-8859-1" />

        <title>test
        </title>

        <link type="text/css" rel="stylesheet" href="css/main.css" />
        <link type="text/css" rel="stylesheet" href="css/mmenu.5.3.css" />


        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/hammer.js/1.0.5/jquery.hammer.min.js"></script>
        <script type="text/javascript" src="js/umd.all.js"></script>
        <script src="http://cdn.jsdelivr.net/jquery.cookie/1.4.0/jquery.cookie.min.js"></script>

        <script type="text/javascript">

            //  The menu on the left
            $(function() {
                $('nav#menu-left').mmenu();
            });


            //  The menu on the right
            $(function() {

                var $menu = $('form#menu-right');

                $menu.mmenu({
                    offCanvas: {
                       position : "right"
                    },
                    classes     : 'mm-light',
                    dragOpen    : true,
                    counters    : true,    
                     searchfield: {
                        add: true,
                        search: false
                    },
                    labels      : {
                        fixed       : !$.mmenu.support.touch
                    },
                    navbars: {
                        position:   "top",
                         content: [
                                    '<a href="javascript:document.getElementById(\'menu-right\').submit();">Save</a>'
                            ]
                         }

                });

            });
        </script>
    </head>
    <body>
    <?php
    // DB Configuration
$config = parse_ini_file('config/config.ini'); 


    //Timezone dropdown
function timezone() {    
    $list = DateTimeZone::listAbbreviations();
    $idents = DateTimeZone::listIdentifiers();

    $data = $offset = $added = array();
    foreach ($list as $abbr => $info) {
        foreach ($info as $zone) {
            if ( ! empty($zone['timezone_id'])
                AND
                ! in_array($zone['timezone_id'], $added)
                AND
                  in_array($zone['timezone_id'], $idents)) {
                $z = new DateTimeZone($zone['timezone_id']);
                $c = new DateTime(null, $z);
                $zone['time'] = $c->format('h:i a');
                $data[] = $zone;
                $offset[] = $z->getOffset($c);
                $added[] = $zone['timezone_id'];
            }
        }
    }

    array_multisort($offset, SORT_ASC, $data);
    $options = array();
    foreach ($data as $key => $row) {
        $options[$row['timezone_id']] = $row['time'] . ' - '
                                        . formatOffset($row['offset'])
                                        . ' ' . $row['timezone_id'];
    }

    return $options;
}
function formatOffset($offset) {
        $hours = $offset / 3600;
        $remainder = $offset % 3600;
        $sign = $hours > 0 ? '+' : '-';
        $hour = (int) abs($hours);
        $minutes = (int) abs($remainder / 60);

        if ($hour == 0 AND $minutes == 0) {
            $sign = ' ';
        }
        return 'GMT' . $sign . str_pad($hour, 2, '0', STR_PAD_LEFT)
                .':'. str_pad($minutes,2, '0');

}
?>
        <div id="page">
            <div id="header">
                <a href="#menu-left"></a>
                        <!-- Sub Header -->
                    <form id="tzForm" method="POST" action="">
                    <select name="userTZ" >
                    <?php foreach(timezone() as $key => $tz) { ?>
                    <option value="<?php echo $key; ?>"<?php if ($_POST['userTZ'] == $key) { echo ' selected>';} else { echo '>';} //keep tz as last selected 
                     echo $tz; ?></option>
                    <?php } ?>
                    </select> <input type="submit" value="Set">

                    </form>
                <a href="#menu-right" class="friends right"></a>
            </div> <!-- Close Header -->
            <div id="content">


                <?php


                                //Collect Selected Sport/Category/Event values from right menu

                    if (isset($_COOKIE["cUserPrefs"])) {
                    echo "<script type='text/javascript'>alert('ding ding ding');</script>";
                    } elseif (isset($_SESSION['sesUserPrefs'])) {

                            $sportListItem = $_SESSION['sesUserPrefs'];

                        //update array with selected toggles
                while ($row = $result->fetch_array()) {
                    if ($row['SportCategory'] == $sportListItem OR $row['Sport'] == $sportListItem OR $row['Event'] == $sportListItem)  {
                    $gameArray[ $row['PK_ID'] ] = array(
                                'GameDate' => $row['GameDate'],
                                'Timezone' => $row['Timezone'],
                                'TeamOne' => $row['TeamOne'],
                                'TeamTwo' => $row['TeamTwo'],
                                'urlTeamOne' => $row['urlTeamOne'],
                                'urlTeamTwo' => $row['urlTeamTwo'],
                                'FK_SportData' => $row['FK_SportData']
                                );
                                } //end inside if

                                }; 

                } 


                ?>

            </div>

        <div id="page">

            <div id="content">
                <p id="confirmation"></p>
            </div>
            <nav id="menu-left">
                <?php
                foreach ($sportArray as $ids=>$vals) {

                    //First List Item
                if ($ids == 1) {
                    echo '<ul><li>
                            <a href="?SportID='.$sportArray[$ids]["SportCategory"].'">'. $sportArray[$ids]["SportCategory"]. '</a>
                            <ul class="Vertical">'; 
                         }  
                            //All others check if different to one before
                         elseif ($sportArray[$ids]["SportCategory"] != $sportArray[($ids - 1)]["SportCategory"]) {
                                echo '</ul></li></ul></li><li>
                                        <a href="?SportID='.$sportArray[$ids]["SportCategory"].'">'. $sportArray[$ids]["SportCategory"] . '</a>
                                        <ul class="Vertical">';  //opening thse UL without an event could cause issues
                            }

                    //Check the previous sport is not the same
                if  ($sportArray[$ids]["Sport"] != $sportArray[($ids - 1)]["Sport"]) {
                    echo '<li>
                            <a href="?SportID='.$sportArray[$ids]["Sport"].'">'. $sportArray[$ids]["Sport"] . '</a>
                            <ul class="Vertical">'; 
                        }
                        //Print Event
                    echo '<li>
                            <a href="?SportID='.$sportArray[$ids]["Event"].'">'. $sportArray[$ids]["Event"] . '</a>
                            </li>';


                }

                ?>
                </ul></li></ul></li></ul>   
            </nav>
            <form id="menu-right" method="post" action="">
            <?php
                foreach ($sportArray as $ids=>$vals) {
                    //First List item
                if ($ids == 1) {
                    echo '<ul class="Vertical"><li>
                            <a href="">'. $sportArray[$ids]["SportCategory"]. '</a>
                            <input type="checkbox" class="Toggle" name="sportList[]" value="'.$sportArray[$ids]["SportCategory"].'" />
                            <ul class="Vertical">';
                         }  
                            //All others check if different to one before
                         elseif ($sportArray[$ids]["SportCategory"] != $sportArray[($ids - 1)]["SportCategory"]) {
                                echo '</ul></li></ul></li><li>
                                        <a href="">'. $sportArray[$ids]["SportCategory"] . '</a>
                                        <input type="checkbox" class="Toggle"  name="sportList[]" value="'.$sportArray[$ids]["SportCategory"].'" />
                                        <ul class="Vertical">'; //opening thse UL without an event could cause issues
                            }

                    //Check the previous sport is not the same
                if  ($sportArray[$ids]["Sport"] != $sportArray[($ids - 1)]["Sport"]) {
                    echo '<li>
                            <a href="">'. $sportArray[$ids]["Sport"] . '</a>
                            <input type="checkbox" class="Toggle" name="sportList[]" value="'.$sportArray[$ids]["Sport"].'" />
                            <ul class="Vertical">';
                        }
                        //Print Event
                    echo '<li>
                            <a href="">'. $sportArray[$ids]["Event"] . '</a>
                            <input type="checkbox" class="Toggle" name="sportList[]" value="'.$sportArray[$ids]["Event"].'" />
                        </li>';


                }

                ?>
                </ul></li></ul></li></ul>   
            </form>
        </div>
    </body>
</html>

1 个答案:

答案 0 :(得分:1)

您应该使用会话数组。首先将值存储到会话中。然后你需要:

  

序列化会话数组并应用base64_encode。把这个值   进入cookie。

在开始时检查cookie是否存在然后应用base64_decode并反序列化该数据并推入会话数组。

  

如果你知道序列化,反序列化,base64_encode和   base64_decode然后你可以轻松完成这项任务。

希望你能轻松完成这件事。