渲染EJS

编程入门 行业动态 更新时间:2024-10-22 13:43:01
本文介绍了渲染EJS-节点JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在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

本文发布于:2023-10-27 15:45:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1533822.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:EJS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!