首页 > 解决方案 > 从外部页面加载内容时不刷新页面+为每个页面创建链接

问题描述

我正在尝试创建一个导航栏,它可以从外部文件加载内容而不刷新页面。

例如,我有一些特殊的index.php包含来自source_a.php文件的内容。使用我的导航,我可以放入我的source_b.php文件中的内容和我的index.php不会被重新加载。

问题的第二部分是我需要创建指向我的index.php不同状态的链接。我需要使用source_a.php内容创建指向index.php的链接,或者使用source_b.php内容创建指向index.php的链接。

我找到了一些教程来解释我的问题的第一部分 - 它展示了如何将来自不同页面的外部内容加载到我页面的特定部分(来源:https ://johnmorrisonline.com/jquery-tutorial-ajax-load-content-with -no-page-refresh/)。

<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script>
      $(document).ready(function(){
        // Set trigger and container variables
        var trigger = $('#nav ul li a'),
            container = $('#content');

        // Fire on click
        trigger.on('click', function(){
          // Set $this for re-use. Set target from data attribute
          var $this = $(this),
            target = $this.data('target');       

          // Load target page into container
          container.load(target + '.php');

          // Stop normal link behavior
          return false;
        });
      });
    </script>
  </head>

  <body>
    <nav id="nav">
      <ul>
        <li><a href="#" data-target="home">Home</a></li>
        <li><a href="#" data-target="about">About</a></li>
      </ul>
    </nav>
    <div id="content">
      <?php include('home.php'); ?>
    </div>
  </body>
</html>

但我仍然不知道是否有一种方法可以链接到我的index.php并同时要求我的index.php从特定源(source_d.php而不是默认的source_a.php)加载它的内容。

我尝试过使用它的一些变体:

<a href="index.php" data-target="home">Home</a>

...但没有任何效果。

标签: javascriptjqueryajax

解决方案


推荐阅读