Javascript window.location.href - 刷新页面而不是重定向

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17750298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:28:24  来源:igfitidea点击:

Javascript window.location.href - Refreshes page instead of redirecting

javascriptredirectbrowser

提问by gbam

I'm using window.location.href to redirect my browser and I am not sure why one works and one doesn't. When I use a relative link, it refreshes the current page. When I use the full url it redirects. The page I'm on and the Process.aspx page are on the same directory level. So I should just be able to have a relative link? When I do that though it just reloads the current page I'm on. What basic idea am I missing about window.location.href?

我正在使用 window.location.href 重定向我的浏览器,但我不确定为什么一个有效而另一个无效。当我使用相对链接时,它会刷新当前页面。当我使用完整的 url 时,它会重定向。我所在的页面和 Process.aspx 页面位于同一目录级别。所以我应该能够有一个相对链接?当我这样做时,它只是重新加载我所在的当前页面。我对 window.location.href 缺少什么基本概念?

    $(document).ready(function() {

    $( "button" )
        .button();
    $("#cancel")
        .click(function( event ) {
            alert("click");

            //Below Line Doesn't work
            window.location.href = "/Process.aspx";

            //Below Line Does work
            window.location.href = "http://localhost:65215/Process.aspx";
    });
});

回答by rink.attendant.6

From the Mozilla Developer Network documentation, hrefis the entire URL of the page. The only relative property in that list is path, which is relative to the host or the domain of the page.

来自Mozilla Developer Network 文档href是页面的整个 URL。该列表中唯一的相对属性是path,它与页面的主机或域相关。

You may also want to look at using the reloador replacemethod. See How to redirect to another webpage in JavaScript/jQuery?

您可能还想查看使用reloadorreplace方法。请参阅如何在 JavaScript/jQuery 中重定向到另一个网页?

回答by Splendiferous

Try: location.href = location.origin + "/Process.aspx";

尝试: location.href = location.origin + "/Process.aspx";

回答by serginhofogo

you can try a hack that only refresh the page, you can implement onclick="location.href='wherever'"and a second href="/Process.aspx"onclickwill be fired first and hrefwill take you back.

您可以尝试仅刷新页面的 hack,您可以实施,onclick="location.href='wherever'"然后href="/Process.aspx"onclick将首先触发第二个href并将带您返回。

回答by GANI

Try this:

试试这个:

window.location = window.location.protocol + 
                  '//' +
                  window.location.hostname +
                  window.location.pathname;