How to load a URL in my single page JavaScript app using Browser history state? -


i wanting use history state in javascript app.

this jsfiddle example https://jsfiddle.net/xyft1pfa/ changes url these values when links clicked on:

  • /page-1/
  • /page-2/
  • /page-3/

my question how go making these url's load content app if accessed these urls directly in browser?

currently if so, tries find page/endpoint on server load not exist.

clicking link load page 3 update url /page-3/ if manually load /page-3/ address bar load 404 missing page file doesn't exist. wanting figure out way make load single page js app , load right content on page when url accessed in manner.

i not using framework.

// should ajax method. // , load url content var setcurrentpage = function(url) {   $('h2 span').html(url || "/");   $("#menu-nav a[href='" + url + "']").fadeto(500, 0.3); };  $('#menu-nav a').click(function(e) {   e.preventdefault();   var targeturl = $(this).attr('href'),     targettitle = $(this).attr('title');    $("#menu-nav a[href='" + window.location.pathname + "']").fadeto(500, 1.0);    window.history.pushstate({     url: "" + targeturl + ""   }, targettitle, targeturl);   setcurrentpage(targeturl); });  window.onpopstate = function(e) {   $("#menu-nav a").fadeto('fast', 1.0);   setcurrentpage(e.state ? e.state.url : null); }; 

html

<h2>current page: <span>/</span></h2> <ul id="menu-nav">   <li><a href="/page-1/" title="pagina 1">page 1</a></li>   <li><a href="/page-2/" title="pagina 2">page 2</a></li>   <li><a href="/page-3/" title="pagina 3">page 3</a></li> </ul> 

in setcurrentpage load page data server ajax request:

var serverbase = "http://example.com/getpage?page="; var setcurrentpage = function(url) {   $.getjson(serverbase + url, function(json){     $('h2 span').html(json.html);     $("#menu-nav a[href='" + url + "']").fadeto(500, 0.3);   }); }; 

and server respond via json:

{"html": "<div>got server</div>"} 

you'll need set correct url according expect in server.

you might ideas how use #hash of location single-page websites: might have @ idea: https://github.com/browserstate/history.js/wiki/intelligent-state-handling


Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -