选择带JSON的AJAX

Select2 AJAX with JSON

本文关键字:AJAX JSON 选择      更新时间:2023-09-26

我一直在尝试使用提供的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 }; 
            }
        }
    });
});