如何在php中获取cookie而不刷新页面? [英] How to get a cookie in php without refreshing the page?

查看:346
本文介绍了如何在php中获取cookie而不刷新页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有这个代码和两个问题:

I currently have this code and two problems:

我得到用户时区与Javascript,并通过ajax发布到timezone.php,用户时间。如果未设置Cookie,则首次访问时,必须刷新该网页才能显示Cookie值。我这样做与JavaScript的时刻,但还有另一种方式。此外,由于网页刷新时没有Cookie,因此禁用Cookie的用户会得到一个刷新循环。

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?

谢谢您,
Markus

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);
}

?>


推荐答案

您可以使用JQuery Plugin https://github.com/carhartl/jquery-cookie ,并检查您的$ .post方法中是否设置了Cookie

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);
});

这篇关于如何在php中获取cookie而不刷新页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆