Ajax - jquery change the URL address without redirecting

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

Possible Duplicate:
http://stackoverflow.com/questions/1457/modify-address-bar-url-in-ajax-app-to-match-current-state http://stackoverflow.com/questions/1457/modify-address-bar-url-in-ajax-app-to-match-current-state


How can I change the URL address without redirecting the page?

For instance, when I click on this link below:

http://mysite.com/projects/article-1 http://mysite.com/projects/article-1 </pre>

I will grab the URL from the link:

var path = object.attr( href );

If I do this below, the page will be redirected:

window.location = path;

http://www.pentagram.com/work/#/all/all/newest/ http://www.pentagram.com/work/#/all/all/newest/

Answers

NOTE: history.pushState() is now supported - see other answers.

You cannot change the whole url without redirecting, what you can do instead is change the hash .

The hash is the part of the url that goes after the # symbol. That was initially intended to direct you (locally) to sections of your HTML document, but you can read and modify it through javascript to use it somewhat like a global variable .


If applied well, this technique is useful in two ways:

    • the browser history will remember each different step you took (since the url+hash changed)
    • you can have an address which links not only to a particular html document, but also gives your javascript a clue about what to do. That means you end up pointing to a state inside your web app.

  To change the hash you can do:   
document.location.hash = "show_picture";

  To watch for hash changes you have to do something like:   
window.onhashchange = function(){
    var what_to_do = document.location.hash;    
    if (what_to_do=="#show_picture")
        show_picture();
}

Of course the hash is just a string, so you can do pretty much what you like with it. For example you can put a whole object there if you use JSON to stringify it.

There are very good JQuery libraries to do advanced things with that.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/6478485/jquery-change-the-url-address-without-redirecting

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils