Javascript 使用 HTML5 History API (Pushstate?) 的好教程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4015613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:09:00  来源:igfitidea点击:

Good tutorial for using HTML5 History API (Pushstate?)

javascripthtmlpushstatehtml5-history

提问by Mild Fuzz

I am looking into using the HTML5 History API to resolve deep linking problems with AJAX loaded content, but I am struggling to get off the ground. Does any one know of any good resources?

我正在考虑使用 HTML5 History API 来解决 AJAX 加载内容的深层链接问题,但我正在努力起步。有谁知道有什么好的资源吗?

I want to use this as it seems a great way to allow to the possibility of those being sent the links may not have JS turned on. Many solutions fail when someone with JS sends a link to someone without.

我想使用它,因为它似乎是一种很好的方式,可以让那些被发送链接的人可能没有打开 JS。当有 JS 的人向没有 JS 的人发送链接时,许多解决方案都会失败。

My initial research seems to point to a History API within JS, and the pushState method.

我最初的研究似乎指向 JS 中的 History API 和 pushState 方法。

http://html5demos.com/history

http://html5demos.com/history

回答by balupton

For a great tutorial the Mozilla Developer Network page on this functionality is all you'll need: https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history

有关此功能的 Mozilla 开发人员网络页面是一个很棒的教程,您只需要:https: //developer.mozilla.org/en/DOM/Manipulating_the_browser_history

Unfortunately, the HTML5 History API is implemented differently in all the HTML5 browsers (making it inconsistent and buggy) and has no fallback for HTML4 browsers. Fortunately, History.jsprovides cross-compatibility for the HTML5 browsers (ensuring all the HTML5 browsers work as expected) and optionally provides a hash-fallback for HTML4 browsers (including maintained support for data, titles, pushState and replaceState functionality).

不幸的是,HTML5 History API 在所有 HTML5 浏览器中的实现方式不同(使其不一致且有问题),并且对于 HTML4 浏览器没有回退。幸运的是,History.js为 HTML5 浏览器提供了交叉兼容性(确保所有 HTML5 浏览器按预期工作),并可选择为 HTML4 浏览器提供哈希回退(包括对数据、标题、pushState 和 replaceState 功能的维护支持)。

You can read more about History.js here: https://github.com/browserstate/history.js

您可以在此处阅读有关 History.js 的更多信息:https: //github.com/browserstate/history.js

For an article about Hashbangs VS Hashes VS HTML5 History API, see here: https://github.com/browserstate/history.js/wiki/Intelligent-State-Handling

有关 Hashbangs VS Hashes VS HTML5 History API 的文章,请参见此处:https: //github.com/browserstate/history.js/wiki/Intelligent-State-Handling

回答by Kiran Aghor

I benefited a lot from 'Dive into HTML 5'. The explanation and demo are easier and to the point. History chapter - http://diveintohtml5.info/history.htmland history demo - http://diveintohtml5.info/examples/history/fer.html

我从“深入 HTML 5”中受益匪浅。解释和演示更简单明了。历史章节 - http://diveintohtml5.info/history.html和历史演示 - http://diveintohtml5.info/examples/history/fer.html

回答by Mauvis Ledford

Keep in mind while using HTML5 pushstate if a user copies or bookmarks a deep link and visits it again, then that will be a direct server hit which will 404 so you need to be ready for it and even a pushstate js library won't help you. The easiest solution is to add a rewrite rule to your Nginx or Apache server like so:

请记住,在使用 HTML5 pushstate 时,如果用户复制或为深层链接添加书签并再次访问它,那么这将是一个直接的服务器命中 404,因此您需要为此做好准备,甚至 pushstate js 库也无济于事你。最简单的解决方案是向 Nginx 或 Apache 服务器添加重写规则,如下所示:

Apache (in your vhost if you're using one):

Apache(在您的虚拟主机中,如果您正在使用):

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.html [L]
 </IfModule>

Nginx

nginx

rewrite ^(.+)$ /index.html last;
rewrite ^(.+)$ /index.html last;

回答by Erik Ringsmuth

The HTML5 history specis quirky.

HTML5规范的历史是古怪。

history.pushState()doesn't dispatch a popstateevent or load a new page by itself. It was only meant to push state into history. This is an "undo" feature for single page applications. You have to manually dispatch a popstateevent or use history.go()to navigate to the new state. The idea is that a router can listen to popstateevents and do the navigation for you.

history.pushState()不会自行调度popstate事件或加载新页面。它只是为了将国家推向历史。这是单页应用程序的“撤消”功能。您必须手动调度popstate事件或使用history.go()导航到新状态。这个想法是路由器可以侦听popstate事件并为您导航。

Some things to note:

一些注意事项:

  • history.pushState()and history.replaceState()don't dispatch popstateevents.
  • history.back(), history.forward(), and the browser's back and forward buttons do dispatch popstateevents.
  • history.go()and history.go(0)do a full page reload and don't dispatch popstateevents.
  • history.go(-1)(back 1 page) and history.go(1)(forward 1 page) do dispatch popstateevents.
  • history.pushState()并且history.replaceState()不发送popstate事件。
  • history.back(), history.forward(), 和浏览器的后退和前进按钮会分派popstate事件。
  • history.go()history.go(0)进行整页重新加载并且不分派popstate事件。
  • history.go(-1)(back 1 page) 和history.go(1)(forward 1 page) 执行调度popstate事件。

You can use the history API like this to push a new state AND dispatch a popstate event.

您可以像这样使用历史 API 来推送新状态并分派 popstate 事件。

history.pushState({message:'New State!'}, 'New Title', '/link'); window.dispatchEvent(new PopStateEvent('popstate', { bubbles: false, cancelable: false, state: history.state }));

history.pushState({message:'New State!'}, 'New Title', '/link'); window.dispatchEvent(new PopStateEvent('popstate', { bubbles: false, cancelable: false, state: history.state }));

Then listen for popstateevents with a router.

然后popstate用路由器监听事件。

回答by deb

Here is a great screen-cast on the topic by Ryan Bates of railscasts. At the end he simply disables the ajax functionality if the history.pushState method is not available:

这是 Railscasts 的 Ryan Bates 就该主题进行的精彩截屏。最后,如果 history.pushState 方法不可用,他会简单地禁用 ajax 功能:

http://railscasts.com/episodes/246-ajax-history-state

http://railscasts.com/episodes/246-ajax-history-state

回答by Oliver Nightingale

You could try Davis.js, it gives you routing in your JavaScript using pushState when available and without JavaScript it allows your server side code to handle the requests.

您可以尝试Davis.js,它可以在可用时使用 pushState 在您的 JavaScript 中路由,如果没有 JavaScript,它允许您的服务器端代码处理请求。

回答by Nathan Totten

You may want to take a look at this jQuery plugin. They have lots of examples on their site. http://www.asual.com/jquery/address/

你可能想看看这个 jQuery 插件。他们的网站上有很多例子。http://www.asual.com/jquery/address/

回答by aknuds1

I've written a very simple router abstraction on top of History.js, called StateRouter.js. It's in very early stages of development, but I am using it as the routing solution in a single-page application I'm writing. Like you, I found History.js very hard to grasp, especially as I'm quite new to JavaScript, until I understood that you really need (or should have) a routing abstraction on top of it, as it solves a low-level problem.

我在 History.js 之上编写了一个非常简单的路由器抽象,称为StateRouter.js。它处于开发的早期阶段,但我将它用作我正在编写的单页应用程序中的路由解决方案。和你一样,我发现 History.js 很难掌握,尤其是我对 JavaScript 还很陌生,直到我明白你真的需要(或应该有)在它之上的路由抽象,因为它解决了一个底层问题。

This simple example code should demonstrate how it's used:

这个简单的示例代码应该演示它是如何使用的:

var router = new staterouter.Router();
// Configure routes
router
  .route('/', getHome)
  .route('/persons', getPersons)
  .route('/persons/:id', getPerson);
// Perform routing of the current state
router.perform();

Here's a little fiddleI've concocted in order to demonstrate its usage.

这是我为了演示它的用法而编造的一个小小提琴

回答by sprugman

if jQuery is available, you could use jQuery BBQ

如果 jQuery 可用,你可以使用jQuery BBQ