如何在不重新加载页面的情况下使用javascript/jQuery更新URL或查询字符串?

arv*_*sim 74 javascript jquery

有没有办法以编程方式更新URL而无需重新加载页面?

编辑:我在帖子中添加了标题中的内容.我只是想明确表示我不想重新加载页面

Fab*_*sco 90

是的,不是.所有常见的Web浏览器都有一个安全措施来防止这种情况.目标是阻止人们创建网站的副本,更改URL以使其看起来正确,然后能够欺骗人们并获取他们的信息.

但是,一些HTML5兼容的Web浏览器已经实现了一个历史API,可以用于类似于您想要的东西:

if (history.pushState) {
    var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?myNewUrlQuery=1';
    window.history.pushState({path:newurl},'',newurl);
}
Run Code Online (Sandbox Code Playgroud)

我测试过,它工作正常.它不会重新加载页面,但它只允许您更改URL查询.您将无法更改协议或主机值.

欲获得更多信息:

http://diveintohtml5.info/history.html

https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history


Mat*_*ows 40

是的 - document.location = "http://my.new.url.com"

你也可以用同样的方式检索它,例如.

var myURL = document.location;
document.location = myURL + "?a=parameter";
Run Code Online (Sandbox Code Playgroud)

location对象也有许多有用的属性:

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
Run Code Online (Sandbox Code Playgroud)

编辑: 设置document.location的哈希值不应该重新加载页面,只需改变焦点所在页面的位置即可.因此更新为#myId将滚动到元素id="myId".如果id不存在我相信什么都不会发生?(虽然需要在各种浏览器上确认)

EDIT2:为了说清楚,而不仅仅是在评论中:您无法在不更改页面的情况下使用javascript更新整个URL,这是一个安全限制.否则,您可以点击指向随机页面的链接,精心设计为gmail,并立即将URL更改为www.gmail.com并窃取人们的登录详细信息.
您可以在某些浏览器上更改域之后的部分以应对AJAX样式的内容,但这已经被Osiris链接.更重要的是,你可能不应该这样做,即使你可以.该URL告诉用户他/她在您的网站上的位置.如果您在不更改页面内容的情况下进行更改,则会变得有点混乱.

  • 设置`document.location`重新加载页面. (19认同)
  • 您无法在不更改页面的情况下使用javascript更新整个URL,这是一个安全限制.否则,您可以点击指向随机页面的链接,并立即将URL说成www.gmail.com并窃取人们的登录信息. (4认同)

Sud*_*Sud 7

您可以使用 :

window.history.pushState('obj', 'newtitle', newUrlWithQueryString)
Run Code Online (Sandbox Code Playgroud)


Pra*_*lva 5

window.history.replaceState({}, document.title, updatedUri);

不重新加载页面的情况下更新 Url

 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);
 }
Run Code Online (Sandbox Code Playgroud)

不重新加载页面的情况下删除查询字符串

var url = window.location.href;
if (url.indexOf("?") > 0) {
     var updatedUri = url.substring(0, url.indexOf("?"));
     window.history.replaceState({}, document.title, updatedUri);
}
Run Code Online (Sandbox Code Playgroud)