有没有一种方法可以以编程方式更新URL而无需重新加载页面?
编辑:我在帖子的标题中添加了一些内容。我只想清楚一点,就是我不想重新加载页面
有没有一种方法可以以编程方式更新URL而无需重新加载页面?
编辑:我在帖子的标题中添加了一些内容。我只想清楚一点,就是我不想重新加载页面
Answers:
是的- document.location = "http://my.new.url.com"
您也可以使用相同的方式检索它,例如。
var myURL = document.location;
document.location = myURL + "?a=parameter";
位置对象也具有许多有用的属性:
hash Returns the anchor portion of a URL
host Returns the hostname and port of a URL
hostname Returns the hostname of a URL
href Returns the entire URL
pathname Returns the path name of a URL
port Returns the port number the server uses for a URL
protocol Returns the protocol of a URL
search Returns the query portion of a URL
编辑:
设置document.location的哈希值不应重新加载页面,只需更改焦点在页面上的位置即可。因此,更新到#myId将滚动到id="myId"。如果id不存在,我相信什么都不会发生?(不过需要在各种浏览器上进行确认)
EDIT2:为了清楚起见,不仅仅是在注释中:您不能在不更改页面的情况下使用javascript更新整个URL,这是一个安全限制。否则,您可以单击指向随机页面的链接,该页面的外观类似于gmail,然后立即将URL更改为www.gmail.com,并窃取了用户的登录详细信息。
您可以在某些浏览器上更改域名后的部分,以应对AJAX样式的问题,但这已由Osiris链接到。而且,即使可以,您也可能不应该这样做。该URL告诉用户他/她在您网站上的位置。如果您在不更改页面内容的情况下进行了更改,则会有些混乱。
document.location重新加载页面。
是的,没有。所有常见的Web浏览器都有防止这种情况的安全措施。目的是防止人们创建网站副本,更改URL使其看起来正确,然后能够欺骗人们并获取其信息。
但是,某些与HTML5兼容的Web浏览器已实现了History API,该API可用于类似于您想要的内容:
if (history.pushState) {
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?myNewUrlQuery=1';
window.history.pushState({path:newurl},'',newurl);
}
我进行了测试,并且效果很好。它不会重新加载页面,但仅允许您更改URL查询。您将无法更改协议或主机值。
想要查询更多的信息:
http://diveintohtml5.info/history.html
https://developer.mozilla.org/zh-CN/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
window.location.pathname包含一个斜杠/,并且结果值可以http://my.domain.com/?myNewUrlQuery=1代替http://my.domain.com?myNewUrlQuery=1。
您可以使用 :
window.history.pushState('obj', 'newtitle', newUrlWithQueryString)
使用
window.history.replaceState({},document.title,UpdatedUri);
在不重新加载页面的情况下更新网址
var url = window.location.href;
var urlParts = url.split('?');
if (urlParts.length > 0) {
var baseUrl = urlParts[0];
var queryString = urlParts[1];
//update queryString in here...I have added a new string at the end in this example
var updatedQueryString = queryString + 'this_is_the_new_url'
var updatedUri = baseUrl + '?' + updatedQueryString;
window.history.replaceState({}, document.title, updatedUri);
}
在不重新加载页面的情况下删除查询字符串
var url = window.location.href;
if (url.indexOf("?") > 0) {
var updatedUri = url.substring(0, url.indexOf("?"));
window.history.replaceState({}, document.title, updatedUri);
}
是
document.location是正常的方式。
但是document.location实际上与window.location相同,只是在较旧的浏览器中对window.location的支持更多,因此可能是可取的选择。
在SO上查看此线程以获取更多信息:
带有URL标签的前缀URL更改可避免重定向。
这重定向
location.href += '&test='true';
这不会重定向
location.href += '#&test='true';
普通的javascript:document.location ='http://www.google.com';
但是,这将导致浏览器刷新-如果需要更新URL来实现某种浏览历史记录而不重新加载页面,请考虑使用哈希。如果是这种情况,您可能希望研究jQuery.hashchange。
您需要更具体。“更新网址”是什么意思?这可能意味着自动导航到其他页面,这当然是可能的。
如果您只想更新地址栏的内容而不重新加载页面,请参阅不重新加载页面而修改URL
是-document.location.hash查询