将参数追加到URL而不刷新 [英] Appending parameter to URL without refresh

查看:281
本文介绍了将参数追加到URL而不刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题之前已经提过很多次了,但答案并不足以解决我的问题。我不想更改页面的整个网址。我想在没有刷新的情况下在按钮点击后添加一个参数& item = brand

使用 document.location.search + ='& item = brand'; 可以刷新页面。使用
> window.location.hash =& item = brand; 不添加刷新,而是使用散列参数。我试图删除附加后的哈希,但没有奏效。






此答案和其他许多人建议使用HTML5 History API,特别是 history.pushState 方法,以及旧的浏览器将设置一个片段标识符以防止页面重新加载。但如何?






假设网址是: http://example.com/search。 php?lang = en



如何追加& item = brand HTML5 pushState方法或片段标识符,以便输出如下所示: http://example.com/search.php?lang=en&item=brand 不含页面刷新?






我希望有人可以对如何使用HTML5 pushState将参数附加到现有/当前网址。或者可选地,如何为相同的目的设置片段标识符。一个很好的教程,演示或一小段代码的代码将是很好的。



演示到目前为止我所做的。您的答案将不胜感激。

解决方案

您可以使用 pushState replaceState 方法,即:

  window.history.pushState(object or string,Title,new url); 

OR

  window.history.replaceState(null,null,/ another-new-url); 


I know this has been asked many times before but answers were not descriptive enough to solve my problem. I don't want to change the whole URL of page. I want to append a parameter &item=brand on button click without refresh.

Using document.location.search += '&item=brand'; makes the page refresh.

Using window.location.hash = "&item=brand"; append without refresh but with a hash # which eliminates the usage/effect of the parameter. I tried to remove the hash after appending but that didn't work.


This answer and many others suggest the use of HTML5 History API, specifically the history.pushState method, and for old browsers is to set a fragment identifier to prevent page from reloading. But how?


Assuming the URL is: http://example.com/search.php?lang=en

How can I append &item=brand using HTML5 pushState method or a fragment identifier so the output would be like this: http://example.com/search.php?lang=en&item=brand without a page refresh?


I hope someone can throw some light on how to use the HTML5 pushState to append a parameter to an existing/current URL. Or alternatively how to set a fragment identifier for the same purpose. A good tutorial, demo or piece of code with a little explanation would be great.

Demo of what I've done so far. Your answers would be greatly appreciated.

解决方案

You can use the pushState or replaceState methods, i.e.:

window.history.pushState("object or string", "Title", "new url");

OR

window.history.replaceState(null, null, "/another-new-url");

这篇关于将参数追加到URL而不刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆