Backbone:从 JSON 创建集合
我正在尝试将 JSON(来自 php 的 json_encode)加载到 Backbone JS 集合中。我已将问题简化为:
var myJSON = '[{ "id":"1","name":"some name","description":"hmmm"}]';
var myCollection = new MyCollection(myJSON, { view: this });
并且:
MyObject = Backbone.Model.extend({
id: null,
name: null,
description: null
});
MyCollection = Backbone.Collection.extend({
model: MyObject,
initialize: function (models,options) { }
});
错误:
未捕获类型错误:无法使用“in”运算符在中搜索“id”
未捕获的类型错误:无法使用“in”运算符在类似问题 :Backbone:获取来自服务器的集合
我的 JSON 显然格式正确,我是否遗漏了一些明显的东西?我尝试使用简单的 id: "1" 而不是 "id" 得到相同的结果。
I'm attempting to load JSON (from php's json_encode) into a Backbone JS collection. I've simplified the problem to:
var myJSON = '[{ "id":"1","name":"some name","description":"hmmm"}]';
var myCollection = new MyCollection(myJSON, { view: this });
And:
MyObject = Backbone.Model.extend({
id: null,
name: null,
description: null
});
MyCollection = Backbone.Collection.extend({
model: MyObject,
initialize: function (models,options) { }
});
Error:
Uncaught TypeError: Cannot use 'in' operator to search for 'id' in
Similar Issue: Backbone: fetch collection from server
My JSON certainly appears to be in the right format, am I missing something obvious? I have attempted using simply id: "1" as opposed to "id" with the same result.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的 JSON 仍然是字符串格式。在分配之前将其传递给 JSON.parse:
Your JSON is still in string format. Pass it to JSON.parse before assigning it:
您忘记了模型中的
defaults
哈希值。请参阅文档
You forgot the
defaults
hash in your model.See the documentation
所以我可能完全错过了这一点,但问题似乎是数组周围的“单引号”。也就是说,这个:
应该是:
Php,afik,不添加单引号,所以它应该像将一行:更改
为:
so i maybe missing the point completely but the problems seems to be the 'single quotes' around the array. That is, this:
should be:
Php, afik, doesn't add the single quotes, so it should be as simple as changing a line that says:
to: