pjax 无法在网站上运行

pjax not working on website

所以我一直在尝试让 pjax 在我的网站上运行,但运气不佳。 我想做的是非常基本和简单的。我只想在我的主页上创建两个 link,它们都加载一个公共页面。但是一个 link 会使用 pjax 加载它,因此只会更改 div 的内容,而另一个不会使用 pjax 并因此加载整个页面。

这是我主页的代码(main.html) -

<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8'>
        <title>Pjax Tutorial</title>
        <script src='node_modules/pjax/pjax.js' type="text/javascript"></script>
        <script src='main.js' type="text/javascript"></script>
    </head>
    <body>  
        <h1>Welcome to Pjax tutorial</h1>
        <a id="first-link" class="js-Pjax" href="first.html">First link</a>
        <a id="second-link" href="first.html">Second link</a>   

                <div id="first-div">Index page!</div>
    </body>

</html>

这是 link 都引用的公共页面的代码 (first.html) -

<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8'>
        <title>Pjax Tutorial</title>
        <script src='node_modules/pjax/pjax.js' type="text/javascript"></script>
        <script src='main.js' type="text/javascript"></script>
    </head>
    <body>  
        <h1>Welcome to Pjax tutorial</h1>
        <a id="first-link" class="js-Pjax" href="first.html">First link</a>
        <a id="second-link" href="first.html">Second link</a>   

                <div id="first-div">This is the first page! If you came here from the first link, then you can notice that the page didn't load but only the URL and the contents of this div were changed. Yay! If you came here from the second link then you can notice that the page actually loaded and each and everything was re-executed(JS) and re-applied(CSS) again. Boo!</div>
    </body>

</html>

这是我正在使用的 javascript (main.js) -

var a = new Pjax({
    elements: "a.js-Pjax",
    selectors: ["#first-div"]
});

它应该做的是,如果我点击第一个 link,它应该只是替换 div 的内容并更改页面的 URL,而如果我点击第二个link,它应该加载页面而不是仅仅更改 div 和 URL。

我已经在 play framework (MVC) 中编写了相同的代码并且它运行良好,但根据我的说法,我不应该需要 MVC 来 运行 只有这么多代码。

我从这里得到了 Pjax:https://github.com/MoOx/pjax。通过 npm 安装它。

我已经 运行 Pjax.isSupported() 命令并且返回了 true。

感谢任何帮助!

这里有两点需要注意,结合起来解决了我的问题。

首先,对 main.js 或我编写的 javascript 文件的调用必须在 body 标记的末尾完成。像这样 -

<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8'>
        <title>Pjax Tutorial</title>
        <script src='node_modules/pjax/pjax.js' type="text/javascript"></script>
    </head>
    <body>  
        <h1>Welcome to Pjax tutorial</h1>
        <a id="first-link" class="js-Pjax" href="first.html">First link</a>
        <a id="second-link" href="first.html">Second link</a>   

                <div id="first-div">Index page!</div>
       <script src='main.js' type="text/javascript"></script>
    </body>

</html>

其次,我确实需要一个服务器 运行 让 pjax 工作。它与 play framework 和 npm 一起工作。没有服务器就无法工作。

希望这对某人有所帮助。