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

Javascript 重新加载页面,但不要';不要在IE中滚动到顶部,javascript,Javascript,嗨,我有一个很大的项目管理表。当我单击按钮时,我使用 $.post("update_the_database.php", { mode: 'themode', username: username }, function(result){ window.location.href = window.location.href; }); 这将在后台运行“update\u the\u the_database.php”,然后在

嗨,我有一个很大的项目管理表。当我单击按钮时,我使用

$.post("update_the_database.php", { mode: 'themode', username: username },
            function(result){
                window.location.href = window.location.href;
        });
这将在后台运行
“update\u the\u the_database.php”
,然后在完成后重新加载页面。但是它会回到页面的顶部

我试过:

window.location.href = window.location.href + '#the_id';
但在所有浏览器(如Firefox、Chrome、Safari)中,它都会更改地址栏中的URL,但不会重新加载页面

从这里开始:

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

所以我试着:

window.location.reload(true);
它会重新加载页面并向下滚动到Chrome和Safari中的前一个位置,但不会在IE和Firefox中出现

方法2:

现在它在Firefox中工作了

顺便说一句,如果我使用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);
                }
window.location.hash=“#”;
如果(navigator.appName!=“Microsoft Internet Explorer”){
window.location.reload(true);
}
尽管它只是将散列放入地址栏,即使我转到地址栏并按enter键,它也不会刷新页面。我必须删除散列并按enter重新加载页面。。。(然后滚动到顶部)

而不是每次都在window.location.href中附加“#id”,这在您的案例中会导致问题,因为secoding time 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'
        }
}

对regex示例来说太棒了。。当你用正则表达式解决问题时,你知道他们说什么

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

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


请参见

我能想到的唯一一个技巧是保存
窗口指示的滚动位置。滚动
并将其传递给下一个请求(例如:使用查询字符串)。然后创建一个代码来检查该键是否存在,使用
窗口跳转到该位置。滚动到(0,lastPos)
。如果您不使用任何javascript框架,那么它并不漂亮,需要大量代码(并弄脏您的查询字符串)


如果您这样做是为了定期更新数据,那么也许值得重新设计代码来进行ajax更新;但它甚至不起作用(请参见编辑的问题-它不会刷新页面,只会更改地址栏中的url)window.location.href=window.location.href+'#the_id';甚至不起作用(请参见编辑的问题-它不会刷新页面,只会更改地址栏中的url)
    if(window.location.hash){
window.location.href = window.location.href.replace(window.location.hash,"#mynewhash");}