How to cope with refreshing page with JS History A

2019-01-14 11:59发布

问题:

A small website I was creating (more like fiddling) uses AJAX to load each page. Previously I was changing the hash of the url, this worked great but was ugly, and the user could refresh the page, and it would stay on the same page.

Now I have switched to using pushState in the JS History API, which looks much better, and the back and forward work, but refreshing does not. For example:

Going to: http://example.com/page2 goes to a 404 as there is no real page called page 2. But if I click on the button which uses the pushState method to change the url, it works as it should.

How can allow refreshes, and permalinks with the new History API?

(And how do search engines treat this, seeing as Google had to create a way of indexing hash urls, by making the developer switch to #!, is it possible they will do something similar for the history api in the future?)

回答1:

You shouldn't use pushState to push invalid URLs at all. It's meant to be used in cases where the site works both with and without AJAX - i.e. you push the URL which would result in the same output without AJAX when creating this output with AJAX.

If you want only virtual URLs (like in the pre-pushState era), keep using the hash tag.



回答2:

This is a somewhat old question, but it was one of the top google results. In the pursuit of being helpful, here is my solution.

You can use Apache's Mod_Rewrite to rewrite the url to a central location. For example: example.com/p2 gets its page content from example.com/index.php?page=p2 You can keep your current implementation of the History API and AJAX to get the content and include the following in your .htaccess

<ifModule mod_rewrite.c>
  RewriteEngine On
  RewriteRule ^([^/\.]+)/?$ index.php?page=$1&full=1 [L]
</ifModule>

In your index.php:

<?php
  if(isset($_GET['full']) {
    //Generate the full page here
  }else{
    //Generate just the content for AJAX
  }
?>

This Page is a good primer on using mod_rewrite to redirect an entire website. (Comments 11 & 13 have useful additions as well)



回答3:

I had to redirect 404 errors to the sites homepage (the one that loads the AJAX requests), and then get the last component of the URL, and run the javascript function that loads the page using an AJAX request. Not a great solution but it seems to work well.