我正在尝试使用主干和下划线显示从 ajax 调用获取的数据。
在 FF 中它可以工作,但 Chrome 报告错误:Uncaught ReferenceError: data is not defined
.
(数据指模板数据<% _.each(data, function(g) { %>
)
请参阅下面我的代码。
集合:
define(['backbone','models/aModel'], function(Backbone, aModel) {
var aCollection = Backbone.Collection.extend({
url: "api/a",
model: aModel,
parse: function(response){
return response.data;
}
});
return aCollection;
});
型号:
define(['underscore', 'backbone'], function(_, Backbone) {
var aModel = Backbone.Model.extend({
urlRoot: 'api/b',
});
return aModel;
});
查看:
define(['jquery','underscore','backbone','models/aModel','collections/aCollection','text!templates/a.html'], function($, _, Backbone, aModel, aCollection, aTemplate){
var aView = Backbone.View.extend({
render: function() {
var self = this;
this.collection = new aCollection();
this.collection.fetch({
success: function(collection, response) {
self.$el.html(_.template(aTemplate, {data:self.collection.toJSON()}));
},
error: function(collection, response) {
alert("error");
}
});
return this;
},
});
return aView;
});
模板:
<% _.each(data, function(g) { %>
<tr>
<td><%=g.a%></td>
<td><%=g.b%></td>
<td><%=g.c%></td>
<td><%=g.d%></td>
</tr>
<% }); %>
数据:
{"data": [{"a":"1","b":"name1","c":"0000-00-00","d":x},{"a":"2","b":"name2","c":"0000-00-00","d":y}]}
这是解决方案 替换这个:
self.$el.html(_.template(aTemplate, {data:self.collection.toJSON()}));
这样:
var compiledTemplate = _.template(aTemplate);
self.$el.html(compiledTemplate({data:self.collection.toJSON()}));
最佳答案
我创建了一个 JsFiddle 来提供帮助。
这对我在谷歌浏览器上有用。如果您按照此操作,我想您的问题将会得到解决。
$(function() { var compiled = _.template($("#template").html());
$("#here").html(compiled({ data: [ {"a":"1","b":"name1","c":"0000-00-00","d":"x"}, {"a":"2","b":"name2","c":"0000-00-00","d":"y"} ] }));
});
我猜变量“aTemplate”没有使用 chrome 进行编译。
关于javascript - 从 ajax 调用获取数据并填充模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26039572/