【发布时间】:2014-04-29 14:08:41
【问题描述】:
我有一些 JSON 格式如下:
"games": [{
"gameType": "RPG",
"publishers": [{
"publisher": "Square",
"titles": [{
"title": "Final Fantasy",
"gameReleases": [ 2006, 2008, 2010, 2012, 2013, 2014 ]
}]
}]
}]
我有一个下拉菜单,允许用户选择游戏类型并将填充另一个下拉菜单。 因此,如果用户从下拉列表中选择 RPG,则发布者下拉列表将显示“Square”,当用户选择 Square 时, the titles drop down will show "Final Fantasy", when Final Fantasy is selected the range of dates will be selectable in the relevant drop down.
目前我的游戏类型下拉加载正常,问题在于填充后续下拉。这是我填充第一个下拉列表的代码:
profileSelected: function () {
var myUrl = "webapp/jsonaccount=" + accountcode;
$.ajax({
url: myUrl,
type: "POST",
dataType: "text",
success: function(data) {
var info = JSON.parse(data); //parse the returned data
var getType = _.pluck(info.games, 'gameType'); //select the game types from the JSON
var prepareType = _.map(getType, function(val){ return '<option>'+val + '</option>';}).join(); //create the to be added to the combobox
$('select#gameTypeCombo').html(prepareType).selectpicker('render'); //render the box
$('select#gameTypeCombo').selectpicker('refresh'); //refresh the box
$('select#gameTypeCombo').on('change', function() { //when gameType is chosen do this
//Populate publisher based on GameType: (select#publisher)
// When publisher is selected populate Titles: (select#gameTypeCombo)
// When titles is selected populate gameReleases: (select#releaseDates)
})
}
})
}
我的修改是将此添加到更改功能以填充发布者(没有得到尽可能多的标题,因为这不起作用):
$('select#gameTypeCombo').on('change', function() {
var getPublisher = _.pluck(info.games.gameType, 'publisher');
var preparePublisher = _.map(getPublisher, function(val){ return '<option>' + val + '</option>';}).join();
$('select#publisher').html (preparePublisher).selectpicker('render');
})
我的第一个想法是,这是因为它在我的 AJAX 请求中——这可能并不理想,但它是为了传递 JSON。 但是当我再次输入游戏类型时,它起作用了。
所以我认为我的问题在于出版商取决于标题,而我的代码不知道要返回哪个出版商。我查看了变量,但没有工作,不知道从哪里开始。
感谢任何建议。
--编辑--
我变了
var getPublisher = _.pluck(info.games[0].gameType, 'publisher');
因此,通过添加[0],我实际上得到了返回的数据,这是有道理的,但是要开始硬编码,我希望它可以根据上一个下拉列表而变化。
【问题讨论】:
-
没有人可以建议?
-
也将 JSON 数据传递给 map 的迭代器函数。这样,您的内部函数可以处理选择。一会儿我会试着写一个正式的答案。
标签: javascript jquery json backbone.js drop-down-menu