admin管理员组文章数量:1195536
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.
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.
Share Improve this question edited May 23, 2017 at 10:28 CommunityBot 11 silver badge asked Jan 16, 2012 at 6:05 pws5068pws5068 2,1944 gold badges35 silver badges49 bronze badges3 Answers
Reset to default 13Your JSON is still in string format. Pass it to JSON.parse before assigning it:
var myJSON = JSON.parse('[{"id":1,"name":"some name","description":"hmmm"}]');
You forgot the defaults
hash in your model.
MyObject = Backbone.Model.extend({
defaults: {
id: null,
name: null,
description: null
}
});
See the documentation
so i maybe missing the point completely but the problems seems to be the 'single quotes' around the array. That is, this:
var myJSON = '[{ "id":"1","name":"some name","description":"hmmm"}]';
should be:
var myJSON = [{ "id":"1","name":"some name","description":"hmmm"}];
Php, afik, doesn't add the single quotes, so it should be as simple as changing a line that says:
$my_js = "var myJSON = '" . json_encode($my_array_to_send)) . "';";
to:
$my_js = "var myJSON = " . json_encode($my_array_to_send)) . "; ";
本文标签: javascriptBackbone Create collection from JSONStack Overflow
版权声明:本文标题:javascript - Backbone: Create collection from JSON - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738512922a2090914.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论