我一直在尝试使用提供的 JSON 用 select2 填充我的输入。 这是 JSON:
{
"airports":
[
{
"id": "1",
"code": "AMQ",
"city": "Ambon",
"country": "Indonesia"
},
{
"id": "2",
"code": "BJW",
"city": "Bajawa",
"country": "Indonesia"
}
]
}
以及 html 代码:
<input class="" type='hidden' value="192" data-init-text='Departing City' name='input' id='depart-airport' style="width: 300px"/>
以及js代码:
$(document).ready(function() {
$('#depart-airport').select2({
minimumInputLength: 1,
ajax: {
url: "http://localhost:4000/api/airports.json",
dataType: 'json',
results: function (data) {
return { results: data};
}
}
});
});
控制台没有错误,但是无论我尝试输入它们,它总是说“搜索失败”或者什么都没有。来自 json 的数据从未显示。 你有什么办法可以解决这个问题吗?谢谢之前:)
最佳答案
您的 jQuery 中有一个小错误:
$(document).ready(function() {
$('#depart-airport').select2({
minimumInputLength: 1,
ajax: {
url: "http://localhost:4000/api/airports.json",
dataType: 'json',
results: function (data) {
// You had { results: data }, but your actual information is in data.airports
return { results: data.airports };
}
}
});
});
关于javascript - Select2 AJAX 与 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24947622/