我有一些像这样的JSON格式:
"games": [{
"gameType": "RPG",
"publishers": [{
"publisher": "Square",
"titles": [{
"title": "Final Fantasy",
"gameReleases": [ 2006, 2008, 2010, 2012, 2013, 2014 ]
}]
}]
}]
我有一个下拉菜单,允许用户选择游戏类型,并将填充另一个下拉菜单。所以,如果从下拉用户选择RPG,在选择最终幻想出版商下拉显示“广场”,当用户选择广场,标题下拉会显示“最终幻想”,日期范围将是可选在相关下拉列表中。
目前,我的“游戏类型”下拉列表加载正常,问题在于填充后续的下拉列表。这是我的代码,用于填充第一个下拉列表:
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)
})
}
})
}
我的修正是将其添加到change函数中以填充发布者(开始时标题不尽人意):
$('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]
我实际上得到了返回的数据,这是有道理的,但是要开始进行硬编码,我希望它根据之前的下拉列表是可变的。
我已经设法解决了您的查询。
.change()
在适当填充数据之后,所有的嵌套函数调用都是一堆。如果您在了解帮助器功能方面需要帮助,我将添加注释。:)
您可以在这里看看:JSFiddle
不好意思的格式。您可以将JS复制到您喜欢的文本编辑器并验证正在执行的操作。希望能帮助到你。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句