【发布时间】:2016-07-26 13:35:56
【问题描述】:
我正在尝试从 ajax 调用(它为我提供我需要的 JSON)成功时触发的函数中使用 underscore.js 呈现模板。
我遇到了某种奇怪的行为:
- 第一次ajax调用成功时,报错:
未捕获的引用错误:未定义响应
- 第二次成功时,不刷新页面,一切按预期进行。
我的 JSON 有这样的结构:
{
data: [
item1: {count: "1", url: "http://example1.com", id:"arstd", formatted:"1"},
item2: {count: "53", url: "http://example2.net", id:"hneio", formatted:"0"},
...
]
}
我的 underscore.js 模板:
<script type="text/template" id="count_template">
<% _.each (response.data, function (item) { %>
<a href="<%- item.url %>">
<li>
<p id="<%- item.id %>" class="name">
<%- item.formatted %>
</p>
<p id="<%- item.id %>_count" class="count">
<%- item.count %>
</p>
</li>
</a>
<% }); %>
</script>
我的ajax回调函数:
var on_result_count_fetched = (function () {
var totals = $(".regions .count");
var ajax_loader = $("#ajax_loader");
var c_tl = $('#count_template');
var count_div = $('#res_count');
//getting the template for the count response
if (c_tl) {
var c_template = _.template(c_tl.html());
}
_.templateSettings.variable = "response";
//real callback
return function (response) {
if (response.redirect) {
window.location.replace(data.redirect);
} else {
//hide loading animation
ajax_loader.hide();
if (!response && _.isEmpty(response)) {
var tmp = $("<button>In case of fail: do this other action!</button>")
tmp.click (function() {
fetch_results ("searx");
});
} else {
console.log(response);
var tmp = c_template(response);
}
count_div.empty();
count_div.append(tmp);
}
}
}());
【问题讨论】:
标签: javascript templates underscore.js underscore.js-templating