2017-06-22 42 views
3

好吧,來自noob土地的問題。但我一直試圖讓pjax工作一段時間,似乎沒有任何工作。 我得到的最好的是終端中的進程的確認,但是當我單擊鏈接時,它會將我帶到整個其他頁面,而不是在指定的div中顯示其內容。如何讓PJAX使用Express和EJS?

我還包含一個鏈接到Chris Wanstrath的pjax源代碼。 似乎沒有任何工作。

//The schedule.js file 
 
router.get('/', function(req, res) { 
 
    res.render('schedule', { title: 'Schedule' }); 
 
}); 
 

 
//The jQuery end of the line 
 
$(document).pjax('a[data-pjax]', '#pjax-container');
<li><a data-pjax="#pjax-container" href="/schedule">Schedule</a></li> 
 
    
 
<div id="pjax-container"> 
 
</div>

+0

也許嘗試'router.get('/ schedule',...);'? – Kino

+0

問題已解決,但您的建議無效。試了一下回來。 – Nnanyielugo

回答

2

我發現pjax可以設置正確,還是重新載入頁面,如果你與有效載荷發送<html>標籤,然後它會觸發一個重載 - 也許當你犯了一個請求,這爲什麼你的網頁正在加載?

此外,失敗的請求到服務器的默認超時設置爲大約600毫秒,所以在下面的代碼中,我已經將默認值上調爲5000毫秒。

您需要區分服務器端,請求是針對文檔的一部分還是使用pjax附加到標頭的http標頭"X-PJAX"的完整文檔。

這裏是我的解決方案,這一點使用的NodeJS /快遞5/pjax

創建一個名爲pjax-helper.js包含以下內容的輔助文件

'use strict'; 

module.exports = function() { 
    return function pjax(req, res, next) { 
     if(req.header('X-PJAX')) { 
      req.pjax = true; 
      res.locals.pjax = true; 
     } else { 
      req.pjax = false; 
      res.locals.pjax = false; 
     } 
     next(); 
    }; 
}; 

在您的應用程序,你就可以要求文件

var pjax = require('./include/pjax-helper');

並在一次快遞被加載...

app.use(pjax());

現在你將有兩個您的應用變量和視圖層


在我的情況下,使用EJS模板引擎,我沒有這樣的事情......

//schedule.ejs: 
<%- include('includes/header') %> 
<h1><%= title %></h1> 
<%- include('includes/footer') %> 

-

//includes/header.ejs 
<% if(locals.pjax==false) { %> 
<!DOCTYPE html> 
<html lang="en"> 
    <head> ... </head> 
    <body> 

     <%- include('menu') %> 

     <div id="pjax-container"> 
<% } %> 

-

//includes/footer.ejs 
<% if(locals.pjax==false) { %> 
</div><!--/#pjax-ccontainer--> 

<script src="/js/pjax.js"></script> 
<script> 
    $(document).pjax('a.pjax', '#pjax-container', {timeout: 5000}); 
    $(document).on('pjax:send', function() { $('#loading').show(); }); 
    $(document).on('pjax:complete', function() { $('#loading').fadeOut(); }); 
</script> 

</body> 
</html> 

<% } %> 
+1

儘管我在看到你的答案之前已經找到了答案,但是「包括」頁眉和頁腳卻做到了。特別是在頁面重新加載時。 – Nnanyielugo

+0

@Nnanyielugo很高興一切都已經解決 - 如果你可以將其標記爲已接受的答案,這對其他人會有所幫助 – Tricky

+0

還有一個包使得它變得簡單https://github.com/dakatsuka/express-pjax –