$getJSON结果与jquery.push()和mustache.js
我有一个脚本,我认为它会将$getJSON ajax请求返回的每个新项推送到一个数组中。然后,mustache.js将使用该数组进行模板化。下面是它的样子:$getJSON结果与jquery.push()和mustache.js,jquery,getjson,mustache,Jquery,Getjson,Mustache,我有一个脚本,我认为它会将$getJSON ajax请求返回的每个新项推送到一个数组中。然后,mustache.js将使用该数组进行模板化。下面是它的样子: $(function() { var templateData = new Array(); $.getJSON('views.json', function(data) { $.each(data, function(i, item) { templateData.push({ name
$(function() {
var templateData = new Array();
$.getJSON('views.json', function(data) {
$.each(data, function(i, item) {
templateData.push({
name : item.name
})
});
});
console.log(templateData);
var galleryTemplate = $('#gallery-template').html();
$('body').append(Mustache.render(galleryTemplate, templateData));
}))
我可以在控制台中看到项目没有被推送到阵列中。页面上没有任何错误,但前端没有呈现任何内容,如下所示:
<body>
<script id="gallery-template" type="text/html">
<h1>{{name}}</h1>
</script>
<script src="js/jquery-2.1.1.min.js"></script>
<script src="js/mustache.js"></script>
<script src="js/jquery-mustache.js"></script>
<script src="js/custom.js"></script>
</body>
{{name}}
任何帮助都将不胜感激
谢谢
$.getJSON
是一个异步调用,因此它在控制台.log
和渲染之后执行。将所有这些行移到$.getJSON
回调中,就在$调用之后
$(function() {
$.getJSON('views.json', function(data) {
var templateData = [];
$.each(data, function(i, item) {
templateData.push({
name : item.name
})
});
console.log(templateData);
var galleryTemplate = $('#gallery-template').html();
$('body').append(Mustache.render(galleryTemplate, templateData));
});
});