Javascript Backbone:从 JSON 创建集合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8876303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Backbone: Create collection from JSON
提问by pws5068
I'm attempting to load JSON (from php's json_encode) into a Backbone JS collection. I've simplified the problem to:
我正在尝试将 JSON(来自 php 的 json_encode)加载到 Backbone JS 集合中。我已将问题简化为:
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
未捕获的类型错误:无法使用“in”运算符来搜索“id”
Similar Issue: Backbone: fetch collection from server
类似问题: Backbone:从服务器获取集合
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.
我的 JSON 看起来肯定是正确的格式,我是否遗漏了一些明显的东西?我曾尝试简单地使用 id: "1" 而不是 "id" 具有相同的结果。
采纳答案by kinakuta
Your JSON is still in string format. Pass it to JSON.parse before assigning it:
您的 JSON 仍然是字符串格式。在分配之前将其传递给 JSON.parse:
var myJSON = JSON.parse('[{"id":1,"name":"some name","description":"hmmm"}]');
回答by Paul
You forgot the defaults
hash in your model.
您忘记了defaults
模型中的哈希值。
MyObject = Backbone.Model.extend({
defaults: {
id: null,
name: null,
description: null
}
});
See the documentation
查看文档
回答by ErichBSchulz
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:
Php,afik,不添加单引号,所以它应该像更改一行一样简单:
$my_js = "var myJSON = '" . json_encode($my_array_to_send)) . "';";
to:
到:
$my_js = "var myJSON = " . json_encode($my_array_to_send)) . "; ";