无论页面刷新如何,持续计数器

Continual counter regardless of page refresh

我有一段 jQuery 目前每 5 秒递增一个数字。我遇到的问题是它的客户端,因此每次刷新页面时它都会重置。

相反,我希望计数器继续运行,即使您不在网站上也不管您刷新页面多少次,这就是为什么我认为 PHP 这样的服务器端脚本会更适合我的用例。如果没有,请提出其他建议。

我已经用 jQuery 设置了一个可用的 fiddle:http://jsfiddle.net/f354bzy5/

要重现包含我上述要求的这种影响,PHP 会是什么?

这是我正在使用的Jquery:

//Counter
var counter = 22000000000;
$(".count").html(counter);
  setInterval(function () {
  $(".count").html(counter);
  ++counter;
}, 5000);

你能在 cookie 中存储计数器吗?

document.cookie = counter.

因此,如果用户刷新页面,您可以从 cookie 中获取最后一个值。

归结为两个简单的选择。只需选择更符合您要求的正确选项即可:

选择Cookie:如果你想让服务器端访问计数器。请记住,默认情况下,cookie 会随请求一起发送。

选择本地存储 : 如果您不想每次都随请求一起发送计数器,您应该选择本地存储。

勾选这个DEMO

//Counter
var counter=22000000000;
if(typeof(localStorage.getItem('counts'))!='object')
{
   counter=parseInt(localStorage.getItem('counts'));
}
setInterval(function () {
    $(".count").html(counter);
    ++counter;
    localStorage.setItem('counts',counter);
}, 1000);

突出显示 localStorage

localStorage is an implementation of the Storage Interface. It stores data with no expiration date, and gets cleared only through JavaScript, or clearing the Browser Cache / Locally Stored Data - unlike cookie expiry.

你可以用 localStorage 来完成。我是这样做的。您可以根据需要调整它。

//detecting support for localStorage.
if (window.localStorage) {

    //counterValue already exists in localStorage? Let's use that or set to zero.
    var counterValue = localStorage.counterValue || 0;

    setInterval(function() {
        //increment the counter and store updated vale in localStorage as well.
        localStorage.counterValue = ++counterValue;

        //put it in your HTML if you might
        $(".count").html(counterValue);
    }, 5000);

}

使用 localStorage 和一些实用函数怎么样?请记住,这是一个客户端解决方案,当用户删除浏览器 cache/local 数据等时,item 将被擦除

function isLocalStorage() {
    try {
        return 'localStorage' in window && window['localStorage'] !== null;
    } catch(e) {
        return false;
    }
}

function setCounter(key, val) {
    localStorage.setItem(key, val);
}

function getCounter(key) {
    return parseInt(localStorage.getItem(key), 10);
}

(function() {

    var key = "myCounter";
    var counter = isLocalStorage() && getCounter(key) || 1;
    var $placeholder = $(".count");
    $placeholder.html(counter);

    setInterval(function () {
        counter++;
        $placeholder.html(counter);
        isLocalStorage() && setCounter(key, counter);
    }, 2000);
}());

--Demo--