使用 pushstate 在我的 ajax 网站上加载某些页面



>我正在为我的网站安装一个社交网络共享插件,但我注意到我只能共享一个链接......主索引链接..我将如何使用 pushstate 更改浏览器中的 url,以便在共享时加载我网站上的每个特定页面。使用我的 ajax 代码,我只有一个 URL,那就是 https://trillumonopoly.com。我不熟悉 pushstate,但我读到这就是我想要的。

例如,如果我想在我的网站上社交分享音乐页面,那么当人们点击链接时,它会将他们带到我的网站索引页面,并将该特定页面加载到div 中。我将如何做。

这是我的jquery/ajax代码

$(document).ready(function () {
    loadMainContent('main');
    $('body').delegate('.navMenu', 'click', function (event) {
        event.preventDefault();
        loadMainContent($(this).attr('href'));
    });
});
function loadMainContent(page) {
    $('#main').load('pages/' + page + '.php');
}

如果你有一个像yoursite/someroute这样的网址,那么你会收到一个not found错误。所以你需要告诉 apache 为那些使用 rewrite 的路由提供索引.php。

在document.ready中,您需要检查url(document.location.pathname)并根据路径加载内容。

索引页应始终显示一个加载微调器,该微调器将根据 url 中的路径名替换为实际内容

下面是一些如何执行此操作的简单示例代码:

//if path is /contact then return object with the url to php content page
//  and title of the page
const pathToPage = path => {
  switch (path) {
    case "/contact":
      return {
        url:"/contact.php"
        ,title:"Contact"
        ,path:path
      };
  }
}
//when user navigates back and forward
window.addEventListener(
  "popstate"
  ,event =>
    //only set content, do not mess with history
    onlyLoadmain(
      pathToPage(location.pathname)
    )
);
//load main content with or without messing with history
const loadMainBuilder = (push)=>(page)=> {
  //if page is undefined then path is not of known content
  if(page!==undefined){
    if(push){
      //set the url
      history.pushState(
        {},
        page.title
        ,page.path
      );
    }
    document.title = page.title
    //@todo: should show loading here
    //$('#main').html(loading);
    $('#main').load(
      'pages/' + page.url + '.php'
    );
  }
}
const loadMainAndPush = loadMainBuilder(true);
const onlyLoadmain = loadMainBuilder(false);
//... other code
$(document).ready(function () {
  //load the content of current page
  //  when user gets a url in their email like yoursite/contact the
  //  apache rewrite rule will serve index.php but main content is
  //  showing loading untill your code actually replaces it with something
  onlyLoadmain(pathToPage(location.pathname));
  $('body').delegate('.navMenu', 'click', function (event) {
      event.preventDefault();
      //the element clicked should have href with the path, not the php file path
      //so /contacts not /pages/contacts.php
      loadMainAndPush(pathToPage($(this).attr('href')));
  });
});