刷新页面2次AJAX / javascript和的setTimeout页面、AJAX、setTimeout、javascript

2023-09-11 22:34:17 作者:没错!我就是那么帅!

我必须承认,我也不好使用Ajax,Java的脚本或CSS是诚实的。请宽容我,我需要帮助。我使用的是CMS,我裹在jQuery Mobile的,不能使用元刷新方法。如何让我的页面重载只有2次在指定的时间与下面的code。

I must admit I am not good with Ajax, Java script or CSS to be honest. Please go easy on me I need help. I am using a CMS that I wrapped in Jquery mobile and can't use meta refresh methods. How do I make the page reload only 2 times at specified times with the code below.

<script type="text/javascript">

$(document).ready(function(){
setTimeout(function(){
    window.location.reload();
}, 2000);
});

$(document).ready(function(){
setTimeout(function(){
    window.location.reload();
}, 15000);
});
</script>

这是我遇到的问题是,它忽略了第二个,一直持续在一个循环。我知道有一个简单的解决这个。

The problem that I am having is that it ignores the second one and keeps going in a loop. I know there is a simple solution to this.

推荐答案

您需要的持久性,以克服循环问题。 这是因为每一个页面被重新加载的时候,它的JavaScript进行评估。 你的页面应该记住,它已被重新加载。 ...怎么样? 有很多种方法。可以将参数添加到查询字符串,或者该数据保存在cookie中或在本地存储。你可以跟踪重装服务器端。 每种方法都有自己的优点和缺点。

You need persistence to overcome the loop problem. This is because every time the page gets reloaded, the javascript in it is evaluated. Your page should "remember" that it has been reloaded. ...how? There are many ways. You could add a parameter to the query string, or save this data in a cookie or in the local storage. You could keep track of the reloads server-side. Every approach has its own pros and cons.

下面是一个简单可行的解决方案,接近你正在寻找一个,那使用localStorage的(旧的浏览器不支持的localStorage的 http://caniuse.com/#feat=namevalue-storage )

Here's a simple working solution, close to the one you are looking for, that uses the localStorage (old browsers don't support localStorage http://caniuse.com/#feat=namevalue-storage)

<script type="text/javascript">
    ;(function () {
        var reloads = [2000, 13000],
            storageKey = 'reloadIndex',
            reloadIndex = parseInt(localStorage.getItem(storageKey), 10) || 0;

        if (reloadIndex >= reloads.length || isNaN(reloadIndex)) {
            localStorage.removeItem(storageKey);
            return;
        }

        setTimeout(function(){
            window.location.reload();
        }, reloads[reloadIndex]);

        localStorage.setItem(storageKey, parseInt(reloadIndex, 10) + 1);
    }());
</script>

正如你所看到的,我使用包含某种时间表的数组。为了简单起见,该数组中的每个元素包含milliseconts的数量变化页面自上次重装前等待的时间。

As you can see, I use an array that contains some kind of timeline. To keep things simple, every element of the array contains the number of milliseconts to to wait before changing the page since the last reload.

 
精彩推荐
图片推荐