javascript - Select2 AJAX 与 JSON

标签 javascript jquery ajax json

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

相关文章:

javascript - 如何在 javascript 中存储复杂对象?

javascript - 在 href 中搜索包含特定关键字的元素并隐藏其他元素(在 JavaScript 中)

javascript - 何时将样式表添加到 document.styleSheets

javascript - 我想在我想要的时间每天重新启动倒计时两次

c# - 在 ASP.NET 中键入时显示搜索结果

javascript - 如果状态是某种东西,则执行 .filter 和 .map,否则仅执行 .map

javascript - Angular js - 格式化日期时间以匹配条件

javascript - jQuery AJAX 响应中包含的脚本标记在插入 DOM 时未被评估?

javascript - jQuery 如何垂直和水平居中图像 a.k.a. 图像灯箱?

php - 在 JS 中下载用 PHP 创建的 ZIP 文件