2014-02-09 4 views
2

Я работаю на сайте, который управляет, следующим образом:Как включить кнопку назад на АЯКС странице

$(document).ready(function() { 
    if (!$('#ajax').length) { // Check if index.html was loaded. If not, navigate to index.html and load the hash part with ajax. 
    document.location = document.location.href.substring(0, document.location.href.lastIndexOf('/') + 1) 
     + "#" + document.location.href.substr(document.location.href.lastIndexOf('/') + 1); 
    } 

    if (window.location.hash) // Check if the page is being loaded with a '#'. Load the file. 
    $('#ajax').load(document.location.href.substr(document.location.href.lastIndexOf('#') + 1)); 
}); 

$(document).on("click", "a:not(.regular)", function (e) { 
    var url = this.href; 
    if (url.indexOf("https") != -1 || url.indexOf('.html') == -1) // External link or picture 
    return; 

    e.preventDefault(); 

    $('#ajax').load(url, function() { 
     document.location.href = '#' + url.substr(url.lastIndexOf('/') + 1); 
    }); 
}); 

$(window).on('popstate', function (e) { 
    // Back only! 
    //location.reload(); 
    //$('#ajax').load(this.location); 
}); 

URL-адрес меняется, когда пользователь перемещается, даже когда пользователь нажимает на кнопку назад. Тем не менее, страница не обновляется при навигации, поэтому изменяется только URL-адрес, пока фактическая страница остается неизменной.

Как это исправить?
Fiddle
Actual site

+0

Вы хотите, чтобы вы нажали кнопку «назад», чтобы принудительно перезагрузить страницу с помощью строки запроса в URL-адресе? – Sergio

+0

Да, или просто обычный переход к URL-адресу в истории. Код 'document.ready' будет исправлять страницу. – Jonathan

ответ

1

Добавление страницы identfier после # отвечает за эффект. Все, что стоит за # (фрагмент URL-адреса), должно интерпретироваться браузером локально. Таким образом, возвращаясь с тем же URL-адресом, но другой фрагмент не запускает браузер для «перезагрузки», так как он ожидает, что это будет закладка.

Изменение для реального параметра .....?pageid=over_ons.html или идти с PATH_INFO .../overons.html

Кроме того:

document.location.href.substring(0, document.location.href.lastIndexOf('/') + 1)

просто

document.location.hash

+0

'document.location.href = '?' + url.substr (url.lastIndexOf ('/') + 1) + '#' + url.substr (url.lastIndexOf ('/') + 1); 'Кажется, чтобы сделать работу, спасибо! Но теперь страница дергается при каждом перемещении. Любая идея, что вызывает это? – Jonathan

+0

«Подергивания» вызваны логотипом. Если все логотипы находятся в кеше, он больше не дергается. Предварительная загрузка всех логотипов в невидимые div на каждой странице должна делать трюк –

+0

Он дергается, потому что 'document.location.href = '?'' Заставляет страницу перемещаться. Я закончил его решение, как [это] (http://jsfiddle.net/cXB3a/) – Jonathan

0

использовать массив для хранения истории.

$(document).ready(function() { 

    var history = []; 

    if (!$('#ajax').length) { // Check if index.html was loaded. If not, navigate to index.html and load the hash part with ajax. 
    document.location = document.location.href.substring(0, document.location.href.lastIndexOf('/') + 1) 
     + "#" + document.location.href.substr(document.location.href.lastIndexOf('/') + 1); 
    history.push(document.location.href.substr(document.location.href.lastIndexOf('/') + 1); 
    } 

    if (window.location.hash) // Check if the page is being loaded with a '#'. Load the file. 
    $('#ajax').load(document.location.href.substr(document.location.href.lastIndexOf('#') + 1), function(){ 
     history.push(document.location.href.substr(document.location.href.lastIndexOf('#') + 1)); 
    }); 
}); 

$(document).on("click", "a:not(.regular)", function (e) { 
    var url = this.href; 
    if (url.indexOf("https") != -1 || url.indexOf('.html') == -1) // External link or picture 
    return; 

    e.preventDefault(); 

    $('#ajax').load(url, function() { 
     document.location.href = '#' + url.substr(url.lastIndexOf('/') + 1); 
     history.push(url.substr(url.lastIndexOf('/') + 1); 
    }); 
}); 

$(window).on('popstate', function (e) { 
    $('#ajax').load(history[history.lastIndexOf(document.location.href)-1], function(){ 
     document.location.href = "#" + history[history.lastIndexOf(document.location.href)-1]; 
    }); 
}); 
+0

Это не работает. – Jonathan

0

Я решил как следующие признал, что, хотя он работает, это, вероятно, далеко не самый e legant решение:

var lastLocation = document.location.href; 

$(document).ready(function() { 
    if (!$('#ajax').length) { // Check if index.html was loaded. If not, navigate to index.html and load the hash part with ajax. 
     document.location = document.location.href.substring(0, document.location.href.lastIndexOf('/') + 1) + 
      "#" + document.location.href.substr(document.location.href.lastIndexOf('/') + 1); 
    } 

    if (window.location.hash) // Check if the page is being loaded with a '#'. Load the file. 
     $('#ajax').load(window.location.hash.substr(1)); 
}); 

$(document).on("click", "a:not(.regular)", function (e) { 
    var url = this.href; 
    if (url.indexOf("https") != -1 || url.indexOf('.html') == -1) // External link or picture 
     return; 

    e.preventDefault(); 

    $('#ajax').load(url, function() { 
     var pagename = url.substr(url.lastIndexOf('/') + 1); 
     // Keep track of last location. 
     lastLocation = document.location.href.replace(window.location.hash, "") + '#' + pagename; 
     document.location.href = '#' + pagename; 
    }); 
}); 

window.onpopstate = function (event) { 
    // Test if popstate changed while lastLocation wasn't updated. 
    if (lastLocation != document.location.href) 
     location.reload(); 
    else 
     return; 
}; 
0

При переходе с кнопкой назад ready событие не срабатывает из-за back-forward cache. Вместо этого запускается pageshow event. Вы можете принудительно перезагрузить страницу в обработчике событий pageshow.

window.onpageshow = function(event) { 
    if (event.persisted) { 
     window.location.reload() 
    } 
}; 
Смежные вопросы