Update URL on AJAX call?

前端 未结 5 866
误落风尘
误落风尘 2020-12-25 13:50

Right now the biggest issue I\'m having with using AJAX is the fact that if I use AJAX on a page, go to another page, then use the browser\'s back button to go back anything

相关标签:
5条回答
  • 2020-12-25 14:29

    Nope, this is not possible. Update: It is now possible via the HTML5 History API - see razbakov's answer.

    I hope you realize that you are trying to address an extremely difficult problem.

    Let's say your url looks like

    http://example.com/mypage/
    

    If you change the window location programmatically to

    http://example/mypage/1/
    

    Browser will take over and try to navigate to that page, there goes your fancy ajax code!

    So what's the alternative? You use URL fragment.

    Let's say you have a URL like this,

    http://example.com/anotherpage/#section
    

    Browser will first load http://example.com/anotherpage/ and try to find an anchor named 'section' and scroll to that location. This behavior is exploited by the 'Addresses' plugin. This is similar to how those 'Scroll To Top' links work.

    So if you are on the page

    http://example.com/mypage/
    

    and change the URL to

    http://example.com/mypage/#1
    

    Browser will not load new page but rather try to find anchor named '1' and scroll to that anchor.

    Even if you have managed to add fragments to the URL, it doesn't mean the work is done. If the user presses the back button, DOM will be reset and you will have to parse those fragments and recreate the DOM. It's definitely non-trivial.

    0 讨论(0)
  • 2020-12-25 14:29

    After making AJAX call, we can update the Client URL using history.pushState. Please find the below syntax and example

    Syntax: history.pushState(obj, obj.Title, obj.Url);

    Example:

    var url = "http://example.com/mypage/" + "newParameter=newValue"
    history.pushState(undefined, '', url);
    
    0 讨论(0)
  • 2020-12-25 14:31

    pjax handles this gracefully in modern browser.

    0 讨论(0)
  • 2020-12-25 14:36

    This problem can be solved using history.js. https://github.com/browserstate/history.js

    0 讨论(0)
  • 2020-12-25 14:51

    It's possible with HTML5. You can test as example GitHub or Vkontakte site.

    The best answer is here: Change the URL in the browser without loading the new page using JavaScript

    It says that you can use history.pushState function for those purposes. But this solution will only work in HTML5 compatitable browsers. Otherwise you need to use hash-method.

    0 讨论(0)
提交回复
热议问题