有没有一种方法可以在不重新加载页面的情况下修改当前页面的URL?
如果可能,我想访问#哈希之前的部分。
我只需要更改域之后的部分,所以我不会违反跨域策略。
window.location.href = "www.mysite.com/page2.php"; // this reloads
有没有一种方法可以在不重新加载页面的情况下修改当前页面的URL?
如果可能,我想访问#哈希之前的部分。
我只需要更改域之后的部分,所以我不会违反跨域策略。
window.location.href = "www.mysite.com/page2.php"; // this reloads
当前回答
下面是在不重新加载页面的情况下更改URL的功能。它仅支持HTML5。
function ChangeUrl(page, url) {
if (typeof (history.pushState) != "undefined") {
var obj = {Page: page, Url: url};
history.pushState(obj, obj.Page, obj.Url);
} else {
window.location.href = "homePage";
// alert("Browser does not support HTML5.");
}
}
ChangeUrl('Page1', 'homePage');
其他回答
parent.location.hash = "hello";
您的新url。
let newUrlIS = window.location.origin + '/user/profile/management';
在某种意义上,调用pushState()类似于设置window.location=“#foo”,因为两者都会创建并激活与当前文档相关的另一个历史条目。但是pushState()有一些优点:
history.pushState({}, null, newUrlIS);
您可以签出根目录:https://developer.mozilla.org/en-US/docs/Web/API/History_API
正如Vivart和geo1701所提到的,HTML5 replaceState就是答案。但是,并非所有浏览器/版本都支持此功能。History.js包装了HTML5状态特性,并为HTML4浏览器提供了额外的支持。
下面是在不重新加载页面的情况下更改URL的功能。它仅支持HTML5。
function ChangeUrl(page, url) {
if (typeof (history.pushState) != "undefined") {
var obj = {Page: page, Url: url};
history.pushState(obj, obj.Page, obj.Url);
} else {
window.location.href = "homePage";
// alert("Browser does not support HTML5.");
}
}
ChangeUrl('Page1', 'homePage');
只需使用,它不会重新加载页面,只会重新加载URL:
$('#form_name').attr('action', '/shop/index.htm').submit();