刷新页面2次AJAX / javascript和的setTimeout [英] Reload page 2 times with ajax / javascript and setTimeout

查看:144
本文介绍了刷新页面2次AJAX / javascript和的setTimeout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须承认,我也不好使用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.

这篇关于刷新页面2次AJAX / javascript和的setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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