我想在ajax调用后更新我的视图,从服务器渲染已编译的ejs。
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
无法渲染客户端上的EJS模板
如何在ajax调用快递服务器后使用jquery在ejs上生成内容
因此,据我了解,我应该在服务器上编译我的ejs文件(部分)。
So from what I understand I should compile my ejs file (partial) on the server.
fixtures.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 = ejspile(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) } }) }); });当我启动ajax请求时我没有收到任何错误,但是我也没有得到任何数据或在我的div中更新了HTML
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?
谢谢
推荐答案所以我终于有了一个可行的解决方案:
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 = ejspile(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) } })更多推荐
渲染EJS
发布评论