将数据从ajax GET发送到ejs文件 [英] send data from ajax GET to ejs file
问题描述
我正在使用ajax GET调用检索某些用户数据,并希望在引导卡,这样我就可以使用jQuery在页面上对其进行过滤.
I am retrieving some user data with an ajax GET call, and want to display each user in a bootstrap card, so that I can filter these on the page using jQuery.
当前,我获得了数据,遍历每个用户并将一些卡片元素附加到<div class="card-deck"></div>
:
Currently, I get the data, iterate over each user and append some card elements to the <div class="card-deck"></div>
:
jQuery:
$(document).ready(function() {
$.getJSON('/api/user/all')
.then(data => {
$.each(data, function (i, user) {
var userCard = '<div class="col-md-auto mb-4">' +
'<div class="card matches mx-auto" style="width: 18rem; height: 24rem;">' +
'<div class="card-body">' +
'<h5 class="card-title">' + user.username + '</h5>' +
'<p class="card-text">' + user.jobTitle + '</p>' +
'<p class="card-text">' + user.city + '</p>' +
'</div>' +
"</div>" +
"</div>";
$('#userList').append(userCard);
});
})
})
ejs:
<div class="row">
<div class="card-container align-items-left">
<div class="card-deck" id="userList">
// cards go here ...
</div>
</div>
</div>
这有效,但是将有很多用于构建卡的html,因此,我希望将整个用户对象(在下面是user
)发送到.ejs
文件,以便我可以在此处建立卡:
This works, but there will be a lot of html that goes into building the cards, so I would prefer to send the entire user object (below this is user
) to the .ejs
file, so that I can build the card there:
<div class="row">
<div class="card-container align-items-left">
<div class="card-deck" id="userList">
<div class="col-md-auto mb-4">
<div class="card matches mx-auto" style="width: 18rem; height: 24rem;">
<div class="card-body">
<h5 class="card-title"><%=user.username%></h5>
<p class="card-text"><%=user.jobTitle%></p>
<p class="card-text"><%=user.city%></p>
</div>
</div>
</div>
</div>
</div>
</div>
这是 jQuery数据方法的工作吗?
推荐答案
您需要实现一个终结点,该终结点可获取用户信息并形成userList div的模板,并将数据作为纯HTML字符串发送回去.
You need to implement an endpoint that fetches user information and forms the template for your userList div and sends the data back as a plain html string.
必须通过ajax
调用从客户端调用此端点,并将响应html设置为div
This endpoint has to be called from the client via an ajax
call and set the response html to the div
服务器
app.get('/api/user/all',(req, res){
//get user data
const data = [{username:"john",jobTitle:"a",city:"b"},{username:"doe",jobTitle:"a",city:"b"}];
res.render('userTemplate', {users:data} ,function(err, html) {
res.send(html);
});
客户
$.ajax({
url: "/api/user/all",
cache: false,
success: function(html){
$("#userList").innerHtml(html);
}
});
userTemplate.ejs
<% for(var i=0; i < users.length; i++) { %>
<div class="col-md-auto mb-4">
<div class="card matches mx-auto" style="width: 18rem; height: 24rem;">
<div class="card-body">
<h5 class="card-title"><%= users[i].username %></h5>
<p class="card-text"><%= users[i].jobTitle %></p>
<p class="card-text"><%= users[i].city %></p>
</div>
</div>
</div>
<% } %>
这篇关于将数据从ajax GET发送到ejs文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!