简体   繁体   English

如何在ajax调用expressjs后使用jquery呈现部分ejs模板

[英]How to render part of ejs template with jquery after ajax call on expressjs

I am having trouble finding out how to create part of the DOM on ejs after a jquery ajax call. 在jquery ajax调用之后,我无法找到如何在ejs上创建DOM的一部分。 The feature is a live search which works great and it sends the request to the server, it searches the db and returns a variable containing the list of users based on the search. 该功能是实时搜索,效果很好,它将请求发送到服务器,它搜索数据库并返回包含基于搜索的用户列表的变量。 The problem begins there as EJS doesn't allow partials anymore and the way to embed javascript on html doesn't work on jquery or at least i don't know how. 问题从那里开始,因为EJS不再允许部分,并且在html上嵌入javascript的方式在jquery上不起作用或者至少我不知道如何。 My mind is stuck so any help is greatly appreciated. 我的思绪被卡住,所以任何帮助都非常感激。

This is the Ajax call 这是Ajax调用

$.ajax({
    url: 'http://localhost:3000/contactsearch',
    type: 'post',
    dataType: 'text',
    data: { searchquery: searchquery}
})
.done(function(res){
  var persons = res;
})

The page is rendered by Express this way: 该页面由Express以这种方式呈现:

exports.search = function(req, res){
res.render('./contacts/search', { title: 'Contact search', persons: persons });
};

The request returns an updated persons variable and i need to generate the html for the contact list. 请求返回更新的人员变量,我需要生成联系人列表的html。 I tried many ways but can't get to achieve it. 我尝试了很多方法,但无法实现它。 The way the page is initially rendered is like this so i don't know how to just refresh the list based on the updated persons variable. 页面最初呈现的方式是这样的,所以我不知道如何根据更新的人员变量刷新列表。

HTML goes like this: HTML是这样的:

 <% if (persons.length) { %>
    <% persons.forEach(function(person) { %>
    <div class='contactlistusername'><%= person.username %></div>
    <% })}%>

Try Handling each AJAX updated success result in a different template to render: (in js) 尝试在另一个模板中处理每个AJAX更新的成功结果以进行渲染:(以js为单位)

var renderedData = new EJS({url:'/template/rendering.template'}).render({data:persons});
$('.contact').html(renderedData);

If persons is a array object returmed from your AJAX response, handle in different template file: (in template) 如果person是从AJAX响应返回的数组对象,则处理不同的模板文件:(在模板中)

<% if (persons.length) { %>
<% for(var i in persons) { %>
<div class='contactlistusername'><%= persons[i].username %></div>
<% }} %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM