【问题标题】:Mustache Sending data back to Jquery小胡子将数据发送回 Jquery
【发布时间】: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


【解决方案1】:

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

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

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);
           }
    });
 });

【讨论】:

  • 我明白你的意思。但是让我给你看点东西。我可以使用按钮 onclick 事件隐藏使用模板呈现的元素,也可以更新元素。但它需要 onclick 事件。我不希望这样 :( 我想使用 body onload() 事件之类的东西,但这不起作用。我将更新问题中的按钮代码。
  • @D请再次检查问题。我已经用一点技巧更新了我的问题。但是我需要一点帮助才能在没有点击事件的情况下加载数据。
  • @AhsanShabbir 我已经用一般逻辑更新了答案以更新模板,而无需onclick
  • 感谢您的帮助@DanielShillcock。我真的很感激。
  • 我的荣幸!享受:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-08
  • 2011-08-29
  • 1970-01-01
  • 2013-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多