Advertisement
Guest User

Example history push and pop state

a guest
May 9th, 2015
475
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.     <title>Demo</title>
  5. </head>
  6. <body>
  7.  
  8. <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
  9.  
  10. <a href="#" class="goto" data-service="ip" data-url="http://ip.jsontest.com/?callback=?">IP</a>
  11. <br>
  12. <a href="#" class="goto" data-service="date" data-url="http://date.jsontest.com/?callback=?">Date</a>
  13.  
  14. <script>
  15. var getDataFromUrl = function(url, params, hash, callback) {
  16.     var data = JSON.parse(localStorage.getItem(hash));
  17.  
  18.     if(data) {
  19.         console.log('data from cache');
  20.         callback(data);
  21.     } else {
  22.         $.ajax({
  23.             url: url,
  24.             method: 'GET',
  25.             dataType: 'jsonp',
  26.             jsonp: "callback",
  27.             contentType: "application/json"
  28.         }).success(function(data) {
  29.             localStorage.setItem(hash, JSON.stringify(data));
  30.             callback(data);
  31.         });
  32.     }
  33. };
  34.  
  35. var renderData = function(data) {
  36.     console.log('render data:', data);
  37. };
  38.  
  39. $(".goto").on('click', function(e) {
  40.     e.preventDefault();
  41.     var $this = $(this);
  42.     var url = $this.data('url');
  43.     var params = $this.data('params');
  44.     var hash = $this.data('service');
  45.    
  46.     getDataFromUrl(url, params, hash, function(data) {
  47.         history.pushState({data: data}, null, hash);
  48.         renderData(data);
  49.     });
  50. });
  51.  
  52. window.onpopstate = function(e) {
  53.     e.preventDefault();
  54.  
  55.     if(e.state) {
  56.         var data = e.state;
  57.         renderData(data);
  58.     }
  59. }
  60. </script>
  61.  
  62. </body>
  63. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement