我想從ajax調用(它提供了我需要的JSON)觸發的函數中使用underscore.js呈現模板成功。Underscore.js - 模板不能在第一時間編譯
我遇到了一些奇怪的現象:
- 當AJAX調用成功,第一次,我得到這個錯誤:
Uncaught ReferenceError: response is not defined
- 當它成功了第二次,沒有刷新頁面,一切都按預期進行。
我的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);
}
}
}());