【问题标题】:Render EJS - Node JS渲染 EJS - 节点 JS
【发布时间】:2018-10-26 23:31:05
【问题描述】:

我想在 ajax 调用后更新我的视图,从服务器渲染编译的 ejs。

这两个之前的问题似乎实现了这一点,但我无法更新我的观点

Can't Render EJS Template on Client

How to generate content on ejs with jquery after ajax call to express server

所以据我了解,我应该在服务器上编译我的 ejs 文件(部分)。

fixtures.ejs

<% fixtures.forEach((fixture) => { %>
  <h2><%= fixture.home_team %> vs <%= fixture.away_team %></h2> 
<% }) %>

index.js

app.post('/league_fixtures', async function (req, res) {
  try {
    var league_name = req.body.league_name;
    const fixtures = await leagueFixtures(league_name);

    //compile view
    fs.readFile('./views/fixtures.ejs', "utf-8", function(err, template) {
      fixture_template = ejs.compile(template, { client: true });
      var html = fixture_template({fixtures: fixtures});
      console.log(html);
      // This logs out my HTML with fixtures so I am almost there
      // <h2>Club Africain vs Al-Faisaly Amman</h2>
      // <h2>Al Nejmeh vs ASAC Concorde</h2>
    });
    res.json({fixtures: fixtures });
  } catch (err) {
    res.status(500).send({ error: 'Something failed!' })
  }
});

阿贾克斯

$("a.league-name").on("click", function (e) {
  e.preventDefault();
  var league_name = $(this).text().trim();

  $.ajax({
    url: '/league_fixtures',
    type: 'POST',
    dataType: "json",
    data: { league_name: league_name },
    success: function(fixtures){
     // How do i get HTML from server into here ?
      $('#panel_' + league_name).html(fixtures);
  },
    error: function(jqXHR, textStatus, err){
      alert('text status '+textStatus+', err '+err)
    }
  })
 });
});

我在触发 ajax 请求时没有收到任何错误,但我的 div 中也没有更新任何数据或 HTML

谁能看出我做错了什么?

谢谢

【问题讨论】:

    标签: node.js ajax express ejs


    【解决方案1】:

    所以我终于找到了一个可行的解决方案:

    index.js

    app.post('/league_fixtures', async function (req, res) {
      try {
        const league_name = req.body.league_name;
        const fixtures = await leagueFixtures(league_name);
        const file = await readFile('./views/fixtures.ejs');
        var fixture_template = ejs.compile(file, { client: true });
        const html = fixture_template({fixtures: fixtures});
        res.send({ html: html });
      } catch (err) {
        res.status(500).send({ error: 'Something failed!' })
      }
    });
    

    ajax 调用

    $.ajax({
      url: '/league_fixtures',
      type: 'POST',
      dataType: "json",
      cache: true,
      data: { league_name: league_name },
      success: function(fixtures){
        var html = fixtures['html'];
        $('#panel_' + league_name).html(html);
      },
      error: function(jqXHR, textStatus, err){
        alert('text status '+textStatus+', err '+err)
      }
    })
    

    【讨论】:

      猜你喜欢
      • 2021-04-27
      • 1970-01-01
      • 1970-01-01
      • 2018-12-26
      • 1970-01-01
      • 2019-11-04
      • 2012-01-23
      • 2014-11-03
      • 2012-05-08
      相关资源
      最近更新 更多