Javascript 从JSON填充下拉列表中的数据
我正在从服务器接收JSON,如下所示Javascript 从JSON填充下拉列表中的数据,javascript,jquery,json,backbone.js,marionette,Javascript,Jquery,Json,Backbone.js,Marionette,我正在从服务器接收JSON,如下所示 { "accountType": ["Full","Trial"], "states": [ {"state":"AL","stateDescription":"Alabama","featured":"A1"}, {"state":"AK","stateDescription":"Alaska","featured":"B1"} ], "dates":[ {"dateDescr
{
"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
都应该获得相关数据并填充主干模型默认值
除了目前,只有帐户
类型有效。我不明白为什么这会起作用而其他人不会,因为这是相同的代码。唯一的区别在于JSON数据,accountType
有两条数据<代码>状态有3个,我只想返回其中一个(状态
)
因此,我想我的问题在于指定在
$中检索的数据。getJSON
代码,但许多小时的在线时间都没有给出答案。您的声明数据中的和日期
键都是数组,但您尝试以散列形式访问它们。
如果要从状态数组中提取状态键,可以使用:
有了给定的数据,\uu.pull(data.states,'state')
将为您提供[“AL”,“AK”]
并不是说,如前所述,您的模型可以通过使用model.fetch
大大简化。例如:
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();
},
});
注意在默认值散列中使用数组,改用函数。Mate这绝对是成功的-完美,我对这个主干内容完全陌生,正在努力解决-你已经整理了一些我花了几个小时看的东西!干杯
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();
},
});