2017-11-12 24 views
0

私はウェブサイト上でpjaxを動作させるように努力してきましたが、運が少しありました。 私がしたいことは、とても基本的でシンプルです。私はちょうど共通のページをロードする私のホームページに2つのリンクを作成したい。しかし、1つのリンクはpjaxを使用してロードするため、divの内容を変更するだけで、もう1つはpjaxを使用せずページ全体をロードします。ウェブサイト上で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> 

と、これは両方のリンクは(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> 

、これは私が(main.js)使用しているJavaScriptのである - それは何をすべき

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

は、私が最初のリンクをクリックした場合、それは翔ですuldはdivの内容を置き換えてページのURLを変更しますが、2番目のリンクをクリックするとdivとURLを変更するのではなくページが読み込まれます。

私はプレーフレームワーク(MVC)に同じコードを書いていますが、それは完全に機能していますが、私によればこのコードだけを実行するにはMVCが必要ではありません。

私はここからPjaxを持っています:https://github.com/MoOx/pjax。それをnpmでインストールしました。

私はPjax.isSupported()コマンドを実行しましたが、それはtrueを返しました。

ご協力いただきましてありがとうございます。

答えて

0

ここで気付くべき2つの事柄があり、その組み合わせが私の問題を解決しました。

まず、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> 

第2に、私はpjaxを動作させるためにサーバを稼働させる必要があります。それは、プレイフレームワークとnpmの両方で動作します。サーバーなしでは動作しません。

希望すると、誰かに役立ちます。

関連する問題