【发布时间】:2016-11-11 11:35:04
【问题描述】:
如何将我的 mustache 模板中的数据发送回 JQuery?
您好.. 这是我第一次使用模板库。我的大部分代码都可以正常工作。但此时,我需要从两个不同的来源加载数据。
第一个来源是一个 json 文件,加载所有用户。我有用户名和 ID。
第二个来源需要用户 ID(我在第一个模板中加载)。我想从第一个来源获取数据并将其呈现在模板上。同时,我想将这些 id 发送到 ajax 并从第二个来源加载信息并将其呈现在同一个模板上。
我只需要从第二个来源更新 1 个信息。
如何将此跨度 ID 发送到 ajax 函数?如果它是一个按钮,我可以简单地使用带有 id 的 onclick 事件(工作)。但我必须更新html。我该怎么办?
PS我也不能在一个json中加入两个数据。数据通过 API 传入。
我的小胡子模板
<script id="profile-template" type="text/template">
{#users}}
Your user id is {{id}} <br/>
Your name is {{name}} <br />
Your other information <span id="{{id}}-variable-text">this data has to be loaded from other api </span>
<button onclick="updatetext({{id}});">Update text </button>
{{/users}}
我的 JQuery
<script type="text/javascript">
$(document).ready(function(){
$('#spanID-from-template').html(function(){
// ajax
})
}
我在 ajax 中使用以下代码来命名和来自第一个来源的 ID。 这就是 ajax 成功函数()中发生的事情
var template = $("#profile-template").html();
var html = Mustache.to_html(template, response);
$('#users').append(html);
我添加了一个小技巧来使用 onclick 事件来更新 id 的文本
检查上面的模板和下面的jquery
function updatetext(id){
$("#"+id+"-variable-text").html("updated-text");
}
【问题讨论】:
-
你能提供你的
Mustache.render()吗? -
.render() 不在 jquery 中,对吗?
-
你好。感谢您的快速回复。我的渲染工作完美。但是问题是将用户 ID 发送到另一个我可以加载更多数据的 javascript。我会在一分钟内更新我的问题
-
@SudharsanS 我使用 mustache to_html 而不是 render()。它在 Jquery 中。
-
我相信
to_html()在 Mustache 中已被弃用?请包括response的样子。
标签: javascript jquery html ajax mustache