下划线模板不起作用

时间:2016-08-03 22:24:56

标签: javascript jquery underscore.js underscore.js-templating

在我的HTML中我有:

<input type="button" id="button" value="Click Me!!"></input>

<script type="text/template" id="users-template">
<% _.each(users, function(user){ %>
    <b><%= user.name    %></b> <br />
    <%= user.city   %> <br />
    <%= user.education  %> <br />
<%});%>
</script>

getJSON代码是:

$("#button").click(function(){
    var usertemplate = _.template($("#users-template").html());

    $.getJSON("underscoredata.php", function(data){

        var resultinghtml = usertemplate({users: data.users});

    });

});

</script>

来自underscoredata.php我json_encode数据。最终数据是:

{"users":[{"name":"Daniel","city":"Pune","education":"engineer"},{"name":"Joseph","city":"Bangalore","education":"Doctor"},{"name":"Radhika","city":"Delhi","education":"Actor"}]}

但我在页面上看不到任何内容。如何在页面上显示用户信息&gt;我已经包含了jquery和下划线路径。

感谢。

1 个答案:

答案 0 :(得分:2)

您需要将结果添加到DOM中,创建目标元素:

<div id="target"></div>

并附加resultshtml

...
var resultinghtml = usertemplate({users: data.users});
$('#target').html(resultinghtml);
...