开发者

changing window.location without triggering refresh

I have an AJAX form that submits GET requests. Because these are all GET requests these should be easily bookmark-able. Preferably I'd make my Ajax request, update the screen and then update window.location.开发者_运维问答href to be the URL for the new page.

Unfortunately this reloads the page. Is there any way I can get around this? Basically I'd like the URL bar to be a permalink bar, but it needs to be able to change to keep up with the state of the page.

window.location.hash is no good because that doesn't get sent to the server.


window.history.replaceState( {} , title, new_URL );

This will update the current page URL with a new one without refreshing.

Arguments:

  1. Data object (must be one that could be serialized to text)
  2. The new title of the changed window URL
  3. The URL to change to (without refreshing)

The you could use the window.onpopstate = function(event){...} to listen to events when a user goes back or forward in the browser history and change things however you wish.


The hash is the way to go. Because, as you point out, changes to the hash don't get sent to the server, you have to send an async request to the server as well as updating the hash.

As a simple example, if your URL is http://server.com/page?id=4, when the user triggers the action you send an AJAX request for http://server.com/page?id=4, and set the page URL to http://server.com/page#id=4.

Furthermore, you have to have something to restore the state if the user reloads. This would usually be done by reading the hash value client-side and sending an async request to the server based on the state represented by the hash value.


if you want to do which works in current browser, you can't change window.location.href without reloading the page

your only option is to to change window.location.hash.

you can do that each time you make an ajax call. if you're using jquery, you can bind a function which update the hash each time an ajax call is made. if you choose that you'll have to look for the hash on page load (actually don't know/think you can do that server side) and make that call to have your page on the state corresponding to the hash.

-- update

there is now an API which provide this functionality look for history.pushState, history.replaceState and window.onpopstate : https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history#Adding_and_modifying_history_entries

it's not availlable everywhere yet ( http://caniuse.com/#feat=history ), there is a few polyfill that you can use for the moment that will use this API if it's available and fall back using the url hash


Consider this JavaScript library: https://github.com/browserstate/history.js


Use jquery. It can do ajax requests. You cant use window.location because that is made to change the url.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜