javascript redirect with hash tag

2019-08-08 04:35发布

问题:

I have implemented my website's search results with AJAX, using History.js. For HTML5 browsers, I have URLs like http://example.com/search/X6a2/3, which, in browsers not supporting the History API, does fall back nicely to http://example.com/search/#X6a2/3.

However, if a HTML5 URL is opened in an older browser, the new hash tag is appended to the full URL as soon as the page is changed. (for example http://example.com/search/X6a2/3#/X6a2/4 - ugh!)

All I need is a clean way to redirect to the hash tag-only version as soon as a non-HTML5 browser is detected. window.location.replace() seems to ignore the hash tag. What do I do?

回答1:

This seems to work for me. Are you sure window.replace is the problem?

var href = "http://example.com/search/X6a2/3";
var idx = href.indexOf('search', 0);
var new_href = href.slice(0,idx+7) + "#" + href.slice(idx+7);

alert(new_href);
window.location.replace(new_href);