本文介绍了从URL中删除哈希,将页面加载到无哈希的URL,然后将哈希添加到URL而不重新加载页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个使用AJAX加载和一些jQuery动画的网站。



使用JavaScript,我从动态生成的链接中获取href到基于PHP的页面,然后将该href添加到URL(在不可避免的#/之后)。 / p>

到目前为止一切顺利,除非用户为该页面添加书签并尝试访问该页面,该用户将到达主页,而不是他/她期望的页面访问。



因此,当直接访问页面时,不是通过点击网站的内部链接,我想从网址中删除#/,但保留其后的所有内容,以便像这样书签的URL:

  http://www.mysite.com/#/somepage 

被重写为:

  http://www.mysite.com/somepage 

那么,经过适当的页面( http://www.mysite.com/somepage )已完成加载,我想将#/重新加入其以前的URL( http://www.mysite.com/#/somepage ),无需重新加载页面(由于我正在使用的一个聪明的片段,将确保其余的导航工作方式应该如此。)



所以:


  1. 在页面加载之前,检查URL,如果它有#/ ,请将其删除。

  2. 加载页面位于无哈希网址

  3. 使用#/ 重新显示网址,没有重新加载页面。

它甚至可行吗?如果是的话,我会感激上一堂课。

解决方案

你要做的事情是可行的但是要维护一个完整的PITA,并且它不会在所有浏览器上都可用。除此之外,密钥位于最近扩展的历史对象中,以添加一组新的技巧。其完整文档可从。



你要做的是 replaceState 命令。读取如下:

这将允许您替换浏览器历史记录中的当前页面,但URL中的。 URL将与您拥有的完全一样 - 使用哈希。考虑到您的解决方案,没有必要改变它。



但是,您必须确保无哈希页面重定向到<$ c $的客户端的哈希显示页面c> history object,以保持一致性。这是唯一的要求。


I'm working on a website that uses AJAX loading with some jQuery animations.

With JavaScript, I grab the href from a dynamically generated link to a PHP-based page, and then add that href to URL (after the inevitable #/) .

So far so good, except if a user bookmarks the page and tries to access it, that user will arrive to the home page, instead of the page he/she expected to access.

So, when a page is accessed directly, not by clicking on the internal link of the website, I want to remove #/ from the url, but keep everything after it, so that URL that was bookmarked like this:

http://www.mysite.com/#/somepage

gets rewritten as this:

http://www.mysite.com/somepage

THEN, after the proper page ( http://www.mysite.com/somepage ) finished loading, I want to stick #/ back into its former place in URL ( http://www.mysite.com/#/somepage ), without reloading the page (which, thanks to a clever snippet I'm using, will ensure that the rest of the navigation works the way it should.)

So:

  1. Before page loads, check URL and if it has #/, remove it.
  2. Load page located at hash-less url
  3. Redisplay the url with #/, without reloading the page.

Is it even doable? If yes, I'd be grateful for a lesson.

解决方案

What you are trying to do is doable but an utter PITA to maintain, and it will not be available on all browsers. That aside, the key resides in the history object relatively recently extended to add a new set of "tricks". Its full doc is available from MDN.

What you are after to do this is the replaceState command. Reads as follows:

This will allow you to replace your current page in the history of the browser, but not in the URL. The URL will be exactly as you have it - with the hash. No point changing it considering your solution.

However, you will have to make sure that your hashless page redirects to the hash-present page for clients with the history object, for consistency. That's the only requirement.

这篇关于从URL中删除哈希,将页面加载到无哈希的URL,然后将哈希添加到URL而不重新加载页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 15:06