如何让PJAX与Express和EJS配合使用?

3

好的,这是一道来自新手领域的问题。但我尝试让pjax运行了一段时间,但似乎没有任何进展。 我最好的进展是在终端中获得了该过程的确认,但当我点击链接时,它会将我带到另一个页面,而不是在指定的div中显示其内容。

我还包括了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>


也许尝试使用 router.get('/schedule', ...); - Kino
问题已经解决了,但是你的建议没有起作用。我之前尝试过了。 - Nnanyielugo
1个回答

5
我发现可以正确设置pjax,但如果在载荷中发送<html>标签,则会触发重新加载 - 也许当您发出请求时,这就是为什么您的页面正在加载的原因?
另外,对于向服务器发送的失败请求,默认超时时间设置为约600毫秒,因此在下面的代码中,我将默认值提高到5000毫秒。
您需要通过http header "X-PJAX"来区分服务器端请求是部分文档还是完整文档,而pjax会将其附加到header中。
以下是我使用nodejs / express 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');

一旦Express已加载...

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
@Nnanyielugo 很高兴一切都解决了 - 如果您能将此标记为已接受的答案,对其他人会很有帮助。 - Tricky
还有一个包可以轻松实现这个功能 https://github.com/dakatsuka/express-pjax - Abdalla Arbab

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接