我只需要从JSON文件中获取经过过滤的数据。
有什么办法,我可以像在SQL查询中一样将条件放在ajax调用中。
在我的页面中,我有三个下拉列表,如下所示:-
<select id="artistsList">
<option value="-1"> Select Artist </option>
<option value="1">Artist Abc</option>
<option value="2">Artist Xyz </option>
</select>
<select id="moviesList">
<option value="-1"> Select Movie</option>
<option value="-1"> Abc Movie</option>
<option value="-1"> Xyz Movie Artist </option>
</select>
<select id="songsList">
<option value="-1"> Select Songs</option>
<option value="-1"> Abc Songs</option>
<option value="-1"> Xyz Songs</option>
</select>
另外,我在App_Data文件夹中有一个名为data.JSON的JSON文件,如下所示:-
//json file
[
{
"id": 1,
"movie": "Abc Movie",
"song": "Abc Songs"
},
{
"id": 2,
"movie": "Xyz Movie",
"song": "Xyz Songs"
}
]
//jQuery
$(document).ready(function (e)
{
var getArtistDetails = function (artistId) {
try {
$.ajax({
type: "POST",
async: true,
url: '/App_Data/data.json',
data: { 'artistId': artistId },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data)
{
//need to set the dropdown options as returned data
},
error: function () {
alert('error');
}
});
}
catch (e) {
console.log(e);
}
}
$('#artistsList').change(function (e)
{
var selectedValue = parseInt($(this).val());
console.log(selectedValue);
switch(selectedValue)
{
case 1:
getArtistDetails(selectedValue);
break;
case 2:
getArtistDetails(selectedValue);
break;
case 3:
getArtistDetails(selectedValue);
break;
case 4:
getArtistDetails(selectedValue);
break;
default:
alert('invalid');
break;
}
})
})
现在我的要求是,根据第一个下拉列表的选择,我需要传递artistId并设置其他两个的下拉选项。
最佳答案
我会建议类似(在您的Ajax请求的成功回调中):-
...
success: function (data) {
var movieList = document.querySelector('#moviesList')
var songList = document.querySelector('#songsList ')
movieList.innerHTML = ''
songList.innerHTML = ''
var movieListOption = null
data.forEach(function (item) {
movieListOption = document.createElement('option')
movieListOption.setAttribute('value', item.id)
movieListOption.textContent = item.movie
movieList.appendChild(movieListOption)
songListOption = document.createElement('option')
songListOption.setAttribute('value', item.id)
songListOption.textContent = item.song
songList.appendChild(songListOption)
});
}
...
快乐编码