如何将Ajax获取的用户列表数据传入Mustache模板完成页面渲染
解决方案
仅需调整JS代码逻辑,同时对模板做微小的存放方式调整即可,原有模板的变量匹配逻辑无需修改
1. 调整模板存放方式(避免未渲染的模板标签直接暴露在页面)
你当前直接把Mustache语法写在tbody内,页面初始化时未渲染的{{}}标签会直接展示给用户,建议将模板部分单独放在类型为text/template的script标签内:
<!-- 页面body内新增模板标签 --> <script type="text/template" id="userListTpl"> {{#users}} <tr> <td>{{id}}</td> </tr> {{/users}} </script> <!-- 原有table保留结构即可,tbody清空内容 --> <table class="table table-horizontal table-bordered"> <thead class="thead-strong"> <tr> <th>user number</th> </tr> </thead> <tbody id="tbody"> <!-- 渲染后的内容会自动插入到这里 --> </tbody> </table>
2. 修改index.js的Ajax回调逻辑,增加Mustache渲染步骤
你当前的JS只做了数据打印,没有调用Mustache的渲染方法,也没有把返回数据和模板做绑定,修改后的代码如下:
注意:请确保你的页面已经提前引入了Mustache.js依赖库
update : function () { var data = { adminId: $('#adminId').val(), userId: $('#userId').val() }; $.ajax({ type: 'POST', url: '/api/v1/eduPosts/registerAdminToUser', dataType: 'json', contentType:'application/json; charset=utf-8', data: JSON.stringify(data) }).done(function(data) { // 1. 获取模板字符串 const tpl = $('#userListTpl').html(); // 2. 绑定数据渲染:注意后端返回的是User数组,要对应模板的users字段封装成对象 const renderResult = Mustache.render(tpl, {users: data}); // 3. 将渲染后的HTML插入到页面tbody中 $('#tbody').html(renderResult); }).fail(function (error) { alert(JSON.stringify(error)); }); }
额外说明
如果你不想修改模板的存放方式,也可以直接把tbody内的原有内容当做模板字符串读取,修改渲染逻辑即可,无需新增script模板标签:
// done回调内可以直接这么写 const tpl = $('#tbody').html(); const renderResult = Mustache.render(tpl, {users: data}); $('#tbody').html(renderResult);
内容的提问来源于stack exchange,提问作者sumeen99
相关产品推荐
相关产品推荐

