<!DOCTYPE html> <html> <head> <...> </head> <body> <nav> <a href="//<?=$_SERVER['HTTP_HOST']?>"></a> <a href="/about"> </a> <a href="/contact"> </a> </nav> <div id="content"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatibus, odio. </div> </body> </html>
$(document).ready(function(){ $('a').click(function(e){ e.preventDefault(); var url = $(this).attr('href'); $.ajax({ url: url, data: 'ajax=true', success: function(data){ // , $('#content').html(data.content); } }); window.history.pushState(null, null, url); return false; }); $(window).bind('popstate', function(){ $.ajax({ url: history.location, data: 'ajax=true', success: function(data){ $('#content').html(data.content); } }); }); });
//, : $(document).ready(function(){ $('a[href]').click(function(e){
$(document).ready(function(){ $(document).on('click', 'a[href]', function(e){
$(document).ready(function(){ var pattern = new RegExp("^(https:\/\/"+location.host+"\/|http:\/\/"+location.host+"\/|\/\/"+location.host+"\/|"+location.host+"\/|\/(?!\/))"), // "^\/(?!\/)" - " /, - /" pattern_protocol = new RegExp("^(http:\/\/|https:\/\/|\/\/)"), // , " " pattern_lochost = new RegExp("^("+location.host+")"); $(document).on('click', 'a[href]', function(e){ e.preventDefault(); if(!$(this).attr('href')){console.log('no href'); return false;} var url = $(this).attr('href'), isLocal = (pattern.test(url)) ? true : false; if(isLocal){ console.log('Local link: '+url); if(pattern_protocol.test(url)){url = url.replace(pattern_protocol, '');} if(pattern_lochost.test(url)){url = url.replace(pattern_lochost, '');} // , . .., , "https://domain.com/page" -> "/page". // , domain.com/page, isLocal, // - domain.com/domain.com/page $.ajax({ // : //string data.title //string data.url // bool data.isErrorPage // bool data.hideSidebar // , $('selector').load(data.url+' selector') . // - . url: url, data: 'ajax=true', success: function(data){ reload_page($.parseJSON(data)); } }); window.history.pushState(null, null, url); return false; }else{ console.log('External link: '+url); // , , , location.href/url (, domain.com/google.com) // http://. , https:// - . url = (pattern_protocol.test(url)) ? url : 'http://'+url; window.open(url, '_blank'); } }); $(window).bind('popstate', function(){ $.ajax({ url: location.pathname+location.search, data: 'ajax=true', success: function(data){reload_page(data)} }); }); });
Source: https://habr.com/ru/post/342280/