Cookie或Javascript [英] Cookie or Javascript

查看:150
本文介绍了Cookie或Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为一个游戏制作一个倒数计时器。而问题是,当用户移动到另一个页面时,倒计时无法继续剩余时间。我尝试设置一个cookie和会话,但我不知道。

I am trying to make a countdown timer for a game. And the problem is, when the user move to another page, then countdown cannot continue the remaining time. I am trying to set a cookie and session, but I have no idea about it.

推荐答案

Cookie来回发送每个HTTP请求,因此应该避免存储不必要的变量。

Cookies are sent back and forth with every HTTP request, hence should be avoided for storing unnecessary variables.

为了在服务器端维护计时器,会话是最好的选择。它将自动处理cookie业务,只创建最小的cookie开销来跟踪会话。会话变量存在于服务器上,并通过唯一的cookie连接到HTTP请求。

To maintain the timer on the server-side, a session is the best choice. It will take care of the cookie business automatically, creating only the bare-minimum cookie overhead to keep track of the session. Session variables live on the server, and are connected to HTTP requests by unique cookies.

关于倒计时计时器:由于您无法保持服务器上运行的功能,

Regarding your countdown timer: Since you cannot keep a function running on the server to keep flipping the bits, the best bet is to keep track of the end time.

要在PHP中启动会话,请使用 session_start()。然后将您的值存储在 $ _ SESSION [] 数组中,它们将在请求之间持久化。这里有一个例子:

To initiate a session in PHP, use session_start(). Then store your values in $_SESSION[] array, and they'll persist across requests. Here's an example:

<?php
session_start();
if (!isset($_SESSION['endTime']))
{
    $_SESSION['endTime'] = time() + 60; // end time is 60 seconds from now
    echo "Started a new timer"
}
else if ($_SESSION['endTime'] > time())
{
    echo "Time left: " + ($_SESSION['endTime'] - time());
}
else
{
    echo "Time is up.";
}

这篇关于Cookie或Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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