Ajax / Javascript-仅刷新一次

时间:2018-12-27 07:24:21

标签: javascript php html mysql ajax

如何仅一次不重复地刷新此页面

    function timedRefresh(timeoutPeriod) {
  setTimeout("location.reload(false);",timeoutPeriod);
}

window.onload = timedRefresh(3000);

document.getElementById('myModal').style.display='block';

4 个答案:

答案 0 :(得分:1)

int refresh=0;  

function timedRefresh(timeoutPeriod) {
  setTimeout("location.reload(false);",timeoutPeriod);
  refresh=1;
}

if(refresh==0){
window.onload = timedRefresh(3000);
}


document.getElementById('myModal').style.display='block';

您可以添加标志布尔值或整数来检查是否已加载页面

答案 1 :(得分:0)

您可以使用PHP刷新页面

header('Refresh: 0; url=page1.php');

要刷新当前页面,可以使用-

header("Refresh:0");

答案 2 :(得分:0)

尽管Zeljka的链接答案是未来的证明,但如果您已经使用散列进行导航,则最好使用performance.navigation.type

window.onload = function() {
    if(performance.navigation.type != 1) {
       timedRefresh(3000);
    }
}

function timedRefresh(time) {
    setTimeout(function() {
        location.reload()
    }, time);
}

请注意,NavigationType已过时,但看起来新规范在到达时将具有相同的含义。

答案 3 :(得分:0)

问题是您重新加载了完全相同的页面,因此无法持久保存已运行该代码的事实,它将再次运行它。 做到这一点的老式方法是使用Cookie:

function timedRefreshIfNoCookie(timeoutPeriod, cookieName) {
    var cookies = document.cookie;
    if (cookies.indexOf(' '+cookieName+'=1;') < 0) {
        document.cookie = cookieName+'=1';
        setTimeout(function () {
            location.reload();
        }, timeoutPeriod);
    }
}
window.onload = function() {
    timedRefreshIfNoCookie(3000, 'refreshed');
}    
document.getElementById('myModal').style.display='block';

您可能可以使用更好的东西,例如本地存储或cookie库,以更轻松地使用cookie。