重新加载页面但不要在IE中滚动到顶部

时间:2013-02-12 04:47:35

标签: javascript

嗨,我有一大桌要管理的项目。当我点击按钮时,我使用

$.post("update_the_database.php", { mode: 'themode', username: username },
            function(result){
                window.location.href = window.location.href;
        });

这在后台运行"update_the_database.php",然后在完成后重新加载页面。它可以追溯到页面顶部......

我试过了:

window.location.href = window.location.href + '#the_id';

但是在所有浏览器(IE,Firefox,Chrome,Safari)中,它都会更改地址栏中的URL,但不会重新加载页面。

从这里开始:

Difference between window.location.href=window.location.href and window.location.reload()

如果URL中有锚(#),则“window.location.href = window.location.href将不会重新加载页面 - 在这种情况下,您必须使用window.location.reload()。”

所以我试过了:

window.location.reload(true);

然后重新加载页面并向下滚动到Chrome和Safari中的上一个位置,但不是IE和Firefox ......

How to force a page to reload if all what was changed in url is hash?

方法#2:

window.location.hash = "#" + newhash;
window.location.reload(true);

现在它适用于Firefox ......

BTW如果我使用window.location.reload(true);它在IE中提出:

Windows Internet Explorer

To display the webpage again, the web browser needs to
resend the information you've previously submitted.

If you were making a purchase, you should click Cancel to
avoid a duplicate transaction. Otherwise, click Retry to display
the webpage again.

Retry   Cancel   

您必须按“重试”,否则会出现“网页已过期”的错误页面。

为了避免我正在做的IE弹出窗口:

                window.location.hash = "#<?php echo $id;?>";
                if (navigator.appName != 'Microsoft Internet Explorer') {
                    window.location.reload(true);
                }

虽然它只是将哈希放入地址栏并且即使我转到地址栏并按回车键也不会刷新页面。我必须删除哈希并按回车键重新加载页面...(然后滚动到顶部)

3 个答案:

答案 0 :(得分:1)

不是每次使用window.location.href附加'#id'而导致你的情况下的问题与解密时间一样。window.location.href已经包含一个id并且你附加了另一个id。 在window.location.href上使用正则表达式'/^(.*)#/is'来重新加载之前找到实际的url。现在使用你写的逻辑,即

$.post("update_the_database.php", { mode: 'themode', username: username },
        function(result){
            var str = window.location.href;
            var patt1 = /^(.*)#/;
            window.location.href = patt1.exec(str)[1];
            window.location.href = window.location.href + '#the_id'
        }
}

答案 1 :(得分:1)

Bah到正则表达式的例子..你知道当你用正则表达式解决问题时他们说了什么!

    if(window.location.hash){
window.location.href = window.location.href.replace(window.location.hash,"#mynewhash");}

window.location.hash将包含

  

#符号后面的URL部分,包括#符号。   您可以侦听hashchange事件以获得有关更改的通知   支持浏览器的哈希值。

请参阅mozilla docs

答案 2 :(得分:1)

我唯一能想到的是保存window.scrollY指示的滚动位置并将其传递给下一个请求(例如:使用查询字符串)。然后创建一个代码来检查该密钥是否存在,使用window.scrollTo(0, lastPos)跳转到该位置。如果你不使用任何javascript框架,它并不漂亮,需要大量代码(并且会破坏你的查询字符串)。

如果您这样做是为了定期更新数据,可能需要重新设计代码以进行ajax更新。

相关问题