dqcqcqwq38860 2012-11-10 23:37
浏览 72
已采纳

如何在不刷新页面的情况下在PHP中获取cookie?

I currently have this code and two problems:

I get the users timezone with Javascript and post it to the timezone.php via ajax, which sets a cookie with the users time. If the cookie is not set, say on first visit, the page would have to be refreshed in order to show the cookie value. I'm doing this with javascript at the moment, but there has to be another way. Also, since the page refreshes if there is no cookie, users with cookies disabled would get a refresh loop.

Any suggestions on how to solve these problems?

Thank you, Markus


index.php:

<!DOCTYPE html>
<html>
<head>
<style>
    .night {
        background: #000;
        color: #fff;
    }
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<?php

        if(isset($_COOKIE["time"])) {
            $time = $_COOKIE["time"];
            if($time < 5.5 || $time > 19) {
                $night = true;
            }
        } else {
            echo("
            <script>
              var timezone = new Date().getTimezoneOffset()/60;

              $(document).ready(function() {
                $.post('timezone.php',{timezone: timezone}, function(data){location.reload(true)});
              });
            </script>
            ");
        }
?>

</head>
<body class="<?php echo $night ? "night" : "day"; ?>">
<?php if($night) {
    echo "It's nighttime! ($time)";
} else {
    echo "It's daytime! ($time)";
} ?>
</body>
</html>

timezone.php:

<?php

$timezone = $_POST["timezone"];

if(isset($timezone)) {
    date_default_timezone_set('Etc/GMT'.($timezone <= 0 ? '' : '+').$timezone);
    $time = date("G") + (date("i")/60);
    setcookie("time", $time);
}

?>
  • 写回答

4条回答 默认 最新

  • dongzhansong5785 2012-11-10 23:43
    关注

    You can use JQuery Plugin https://github.com/carhartl/jquery-cookie and check if the cookie is set in your $.post method like that

     $.post('timezone.php',{timezone: timezone}, function(data){
         if ($.cookie("time") != null) 
             location.reload(true);
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line