如何在ajax调用express服务器之后,通过jquery在ejs上生成内容 [英] How to generate content on ejs with jquery after ajax call to express server

查看:98
本文介绍了如何在ajax调用express服务器之后,通过jquery在ejs上生成内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的网站上实现一个搜索功能,所以我做的是用jQuery ajax调用与快速服务器的文本,搜索mongodb并给出匹配的用户的对象数组。现在我成功地收到这个对象,但是由于ejs中没有部分内容,我如何只刷新为每个用户生成html的结果列表?

解决方案

节点EJS包附带一个客户端JavaScript库,位于 ./ node_modules / ejs /ejs.js ./ node_modules / ejs / ejs.min.js 。在您的页面上添加此内容后,您将需要加载模板,然后从模板生成HTML。
检测未定义的对象属性
Javascript示例(在页面加载时加载模板会更加理想):

  function getData(){
/ /获取模板
$ .get('/ results.ejs',function(template){
//编译EJS模板
var func = ejs.compile(template);

//获取数据
$ .get('/ data',function(data){
//从给定的数据生成html
var html = func(data);
$('#divResults')。html(html);
});
});
}

EJS:

 <表> 
< tr>
< th> ID< / th>
< th> Name< / th>
< / tr>
<%data.forEach(function(d){%>
< tr>
< td><% - d.id%>< / td>
< td><% - d.name%>< / td>
< / tr>
<%}); %GT;
< / table>

快递中的Ajax通话:

  app.get('/ data',function(req,res){
res.send({data:[
{id:5,name:'Bill' },
{id:1,name:'Bob'}
]});
});


I want to implement a search feature on my website so what i do is make a jquery ajax call with the text to the express server which searches mongodb and gives an object array of the users that match. Now i receive this object succesfully but since there are no partials on ejs how can i refresh just the results list generating the html for each user?

解决方案

The node EJS packages comes with a client-side javascript library located in ./node_modules/ejs/ejs.js or ./node_modules/ejs/ejs.min.js. After you include this on your page, you'll want to load the template, then generate the HTML from the template. Detecting an undefined object property Javascript Sample (loading the template on page load would be a bit more ideal):

function getData() {
    // Grab the template
    $.get('/results.ejs', function (template) {
        // Compile the EJS template.
        var func = ejs.compile(template);

        // Grab the data
        $.get('/data', function (data) {
           // Generate the html from the given data.
           var html = func(data);
           $('#divResults').html(html);
        });
    });
}

EJS:

<table>
    <tr>
        <th>ID</th>
        <th>Name</th>
    </tr>   
    <% data.forEach(function (d) { %>
    <tr>
        <td><%- d.id %></td>
        <td><%- d.name %></td>
    </tr>
    <% }); %>
</table>

Ajax call in express:

app.get('/data', function (req, res) {
    res.send({ data: [
        { id: 5, name: 'Bill' },
        { id: 1, name: 'Bob' }
    ]});
});

这篇关于如何在ajax调用express服务器之后,通过jquery在ejs上生成内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆