Render EJS - Node JS

梦想与她 提交于 2019-12-24 21:14:12

问题


I would like to update my view after an ajax call, rendering compiled ejs from the server.

These two previous questions seem to achieve this but I cannot update my view

Can't Render EJS Template on Client

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

So from what I understand I should compile my ejs file (partial) on the server.

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!' })
  }
});

Ajax

$("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)
    }
  })
 });
});

I don't get any errors when i fire the ajax request but I also do not get any data or HTML updated in my div

Can anyone see what I am doing wrong?

Thanks


回答1:


So I finally got a working solution:

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 call

$.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)
  }
})


来源:https://stackoverflow.com/questions/50378874/render-ejs-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!