使用 AJAX 加载内容,但在访问时保持完整页面

Loading content using AJAX but keep full page when visiting

这几天我一直在毫不费力地尝试和研究。

基本上,我想要实现的是页面之间的 AJAX。我知道如何使用 AJAX/JQuery 将文件中的内容加载到页面中,但它有点不同。

假设有 2 页。

Index.php Info.php

当我从Index.php点击一个link到Info.php时,只需要替换某个DIV中的内容(如主要内容)

但是,当我访问 Index.php 时,我得到了带有 headers 的完整页面以及所有这些内容。 (明显地) 但是,如果我访问 Info.php,我还想获得包含 headers 和所有内容的完整页面(只是内容不同 DIV)。

我在网站上经常看到这个,但似乎无法找到或弄清楚它是如何工作的。

它也可能基本上只是替换两个页面之间所有不同的东西? (好像是delta loading,好像叫的一样)

所有这一切的主要目的是让音乐播放器在页面加载之间流畅地播放。

任何人都可以解释一下这将如何工作或推动我朝着正确的方向前进吗?

非常感谢! :)

你可以这样做

假设您的页面的所有内容在 #container div

你的导航链接看起来像

<a href="index.php" class="ajax_link">Home<a>
<a href="infor.php" class="ajax_link">Information<a>

在您的 javascript 代码中 jquery

function ajaxPageLoader(request_url) {
    console.log("Content loading from : "+request_url);
    $("#container").load(request_url+" #container", function() {
        window.history.pushState({}, "", request_url); // update current url in browser.
        console.log("Content loaded");
    });
}

function changeState(state) {
    if(state !== null) { // initial page
        ajaxPageLoader(state.url);
    }
}

这是使用 on() 方法

的委托事件处理程序
$(document).ready(function(){
    $(document).on('click','.ajax_link',function(){
        ajaxPageLoader($(this).attr('href'));
        return false;
    });
});
// back button event
$(window).on("popstate", function(e) {
    changeState(e.originalEvent.state);
    return false;
});