【发布时间】: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
谁能看出我做错了什么?
谢谢
【问题讨论】: