[英]Populating data from JSON for drop downs
我正在从看起来像这样的服务器接收JSON
{
"accountType": ["Full","Trial"],
"states": [
{"state":"AL","stateDescription":"Alabama","featured":"A1"},
{"state":"AK","stateDescription":"Alaska","featured":"B1"}
],
"dates":[
{"dateDescription":"Jan","month":1,"year":2008},
{"dateDescription":"Feb","month":2,"year":2008}
]
}
在骨干文件中,我正在做:
define([ 'backbone', 'underscore', 'vent', ], function (Backbone, _, vent) {
'use strict';
return Backbone.Model.extend({
url: {},
loaded: false,
defaults: {
accountType: [],
states: [],
dates: [],
},
initialize: function () {
this.on('change', this.change);
var that = this;
$.getJSON("webapp/jsondata", function (data) {
that.set({
states: data.states.state,
});
});
$.getJSON("webapp/jsondata", function (data) {
that.set({
dates: data.dates.dateDescription,
});
});
$.getJSON("webapp/jsondata", function (data) {
that.set({
accountType: data.accountType,
});
});
},
});
});
因此,每个$.getJSON
应该获取相关数据并填充主干模型默认值。
除非目前只有account
类型有效。 我不明白为什么这样行得通,而其他人则行不通,因为这是同一代码。 唯一的区别在于JSON数据, accountType
有2条数据。 States
有3个,我只想返回其中一个( state
)。
所以我想我的问题是在$.getJSON
代码中指定要检索的数据,但是很多小时在线都没有给出答案。
数据中的states
键和dates
键是数组,但是您尝试将它们作为哈希值进行访问。 如果要从状态数组中提取状态键,可以使用_.pluck
:
$.getJSON("webapp/jsondata", function (data) {
that.set({
states: _.pluck(data.states, 'state')
});
});
有了给定的数据, _.pluck(data.states, 'state')
将给您["AL", "AK"]
并非如所写,通过将model.fetch
与model.parse
一起使用,可以大大简化您的模型。 例如 :
return Backbone.Model.extend({
url: "webapp/jsondata",
loaded: false,
defaults: function () {
return {
accountType: [],
states: [],
dates: [],
};
},
parse: function (data) {
return {
accountType: data.accountType,
states: _.pluck(data.states, 'state'),
dates: _.pluck(data.dates, 'dateDescription')
};
},
initialize: function () {
this.on('change', this.change);
this.fetch();
},
});
当心在defaults
哈希中使用数组,请改用函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.