小胡子正在将数据发送回 Jquery

Mustache Sending data back to Jquery

如何将我的小胡子模板中的数据发送回 JQuery?

你好..这是我第一次使用模板库。我的大部分代码工作正常。但此时,我需要从两个不同的来源加载数据。

第一个来源是一个 json 文件,加载所有用户。我有用户名和ID。 第二个源需要用户标识(我在第一个模板中加载)。我想从第一个来源获取数据并将其呈现在模板上。同时,我想将这些 ID 发送到 ajax 并从第二个来源加载信息并将其呈现在同一模板上。 我只需要从第二个来源更新 1 个信息。 如何将此跨度 ID 发送到 ajax 函数?如果它是一个按钮,我可以简单地使用带有 id 的 onclick 事件(有效)。但是我必须更新html。我该怎么办?
P.S 我也无法将两个数据合并为一个 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 success function()

中发生的事情
              var template = $("#profile-template").html();
              var html = Mustache.to_html(template, response);
              $('#users').append(html);

我添加的一个小 hack 来使用 onclick 事件来更新 id 的文本

检查上方和下方的模板jquery

function updatetext(id){
 $("#"+id+"-variable-text").html("updated-text");

 }

如果您希望使用渲染模板中的数据,您可以执行以下操作...

这里的问题是你正在做的事情的异步性质;从呈现的模板呈现和调用变量。

var template = $("#profile-template").html();
var html = Mustache.to_html(template, response);
$('#users').append(html).promise().done(function(){
   $.ajax({
           url: "url here", 
           success: function(result){
              response = response.concat(result); //Do some reduction here!
              var html = Mustache.to_html(template, response); //This will only render once the promise is fulfilled
              $('#users').append(html);
           },
           error: function(x, s, e){
               console.log(e);
           }
    });
 });