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

时间:2017-10-31 19:26:13

标签: javascript php jquery ajax pushstate

我正在安装一个社交网络共享插件到我的网站,我注意到我只能共享一个链接....主索引链接..我将如何使用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');
}

1 个答案:

答案 0 :(得分:0)

如果您有yoursite/someroute这样的网址,那么您会收到not found错误。因此,您需要告诉apache使用rewrite为这些路由提供index.php。

在document.ready中,您需要检查网址(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')));
  });
});