我有像這樣的格式一些JSON:選擇嵌套的JSON對象和填充下拉菜單
"games": [{
"gameType": "RPG",
"publishers": [{
"publisher": "Square",
"titles": [{
"title": "Final Fantasy",
"gameReleases": [ 2006, 2008, 2010, 2012, 2013, 2014 ]
}]
}]
}]
我有一個下拉,允許用戶選擇遊戲類型,將填充另一個下拉菜單。 因此,如果用戶從下拉列表中選擇RPG,發佈者下拉菜單中將顯示「Square」,當用戶選擇Square時,標題下拉菜單將顯示「最終幻想」,當選擇最終幻想時,日期範圍將會可以在相關的下拉菜單中選擇。
目前我的遊戲類型下拉加載正常,問題是填充隨後的下拉菜單。這是我的代碼來填充第一個下拉:
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。 但是,當我再次通過遊戲類型時,它工作。
所以我認爲我的問題是,發佈者依賴於標題,而我的代碼不知道要返回哪個發佈者。我看着變量,但沒有工作,不知道從哪裏去。
任何意見表示讚賞。
- 編輯 -
我加入[0]
我真正得到返回的數據,是有道理的改變
var getPublisher = _.pluck(info.games[0].gameType, 'publisher');
所以,但是開始這很難在編碼,我希望它是根據變化在前面的下拉菜單中。
沒有人能夠提供建議嗎? – Hagbard
將JSON數據傳遞給map的迭代器函數。這樣,你的內在功能可以處理選擇。我會盡量在一段時間內寫出正式的答案。 – varagrawal