Ich versuche, eine Vorlage mit underscore.js aus der Funktion zu rendern, ausgelöst, wenn ein Ajax-Aufruf (der mir den JSON, den ich brauche) erfolgreich ist.Underscore.js - Vorlage kompiliert nicht beim ersten Mal
ich eine Art seltsamen Verhalten bin erleben:
- Wenn der Ajax-Aufruf zum ersten Mal erfolgreich ist, bekomme ich diesen Fehler:
Uncaught ReferenceError: response is not defined
- Wenn es gelingt, für Beim zweiten Mal, ohne die Seite zu aktualisieren, läuft alles wie gewünscht.
Meine JSON hat diese Struktur:
{
data: [
item1: {count: "1", url: "http://example1.com", id:"arstd", formatted:"1"},
item2: {count: "53", url: "http://example2.net", id:"hneio", formatted:"0"},
...
]
}
Meine Underscore.js Vorlage:
<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>
Meine Ajax-Callback-Funktion:
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);
}
}
}());