Mustache.js - accepts inputs as vars, but not as ajax gets: How to import or troubleshoot
Using this as the example: http://mustache.github.com/#demo, the template and json can functionally be moved to a var:
template = '<h1>{{header}}</h1>{{#items}}{{#first}}<li><strong>{{name}}</strong></li> {{/first}}{{#link}} <li><a href="{{url}}">{{name}}</a></li> {{/link}}{{/items}}{{#empty}} <p>The list is empty.</p>{{/empty}}';
This is where things break down:
$.ajax({
url: "must_template.js",
dataType: "html",
success: function(data) {
template = data;
}
});
and
$.ajax({
url: "theJson2.txt",
dataType: "json",
success: function(data) {
json = data;
//json = $.parseJSON(data);
}
});
Chrome's console shows exactly the same content as the var, but Mustache 开发者_开发百科breaks on the inputs because they're "Undefined" on input:
Uncaught TypeError: Cannot call method 'indexOf' of Undefined
I've tried changing the dataType, parsing it using $.parseJSON and nothing works when importing either the template or JSON from an external file.
If there are any tips for troubleshooting javascript objects, that would be appreciated as well.
Update: Code is here: http://dev.plitto.com/sandbox/mustache_riff/index4.html theJson.txt is the JSON. It's being pulled correctly. console.log(data.header) correctly returns. must_template.js is the Mustache template file (pulling externally will allow for different themes).
AJAX requests are async requests. if you executed mustache to_html outside the ajax function call then it wont work. Because it will be executed before AJAX request.
Try the following.
must_template.html file will contain,
<h1>{{header}}</h1>
{{#items}}{{#first}}
<li><strong>{{name}}</strong></li>
{{/first}}{{#link}} <li><a href="{{url}}">{{name}}</a></li> {{/link}}{{/items}}
{{#empty}} <p>The list is empty.</p>{{/empty}}
And your code will be
$.ajax({
url: "must_template.html",
dataType: "html",
success: function(data) {
var template = data;
$.ajax({
url: "theJson2.txt",
dataType: "json",
success: function(data2) {
var json = data2;
var html = Mustache.to_html(template, json);
$("#yourtargettag").html(html);
}
});
}
});
What is the difference between the two? And what are in theJson2.txt and must_template.js?
Parse JSON with:
data = JSON.parse(data);
And to see what's in the object, use Firebug or the JS Console in Safari / Chrome with:
console.log(data);
If you get some more information up we can be more help :)
Turns out this is a scope problem.
The template variable is defined before the $.ajax() call, and the value is only valid within the $.ajax call.
For a working example of Mustache / jQuery see http://blog.xoundboy.com/?p=535
精彩评论