【问题标题】:Select2 load data from local json fileSelect2 从本地 json 文件加载数据
【发布时间】:2018-05-11 18:33:33
【问题描述】:

我已经设置了 select2 并使用 JS 变量加载数据,但是因为我的数据有很多选项(国家),我想从 a 加载它们而不是在我的JS。

我创建了一个包含所有国家/地区的 countries.json 文件,我正在使用以下代码尝试将它们拉入。但是我收到错误 The results could not be loaded

代码:

$('#allowedCountries').select2({
    placeholder: 'Select allowed countries',
    selectOnClose: false,
    tags: false,
    tokenSeparators: [',', ' '],
    ajax: {
        dataType : "json",
        url      : "includes/countries.json",
        processResults: function (data) {
            return {
                results: $.map(data, function(obj) {
                    return { id: obj.ime, text: obj.ime };
                })
            };
        }
    },
});

countries.json

[{id:1, text: 'Afghanistan'},
{id:2, text: 'Aland Islands'},
{id:3, text: 'Albania'},

...

{id:245, text: 'Yemen'},
{id:246, text: 'Zambia'},
{id:247, text: 'Zimbabwe'}]

【问题讨论】:

  • 您不需要重新处理您的国家/地区结果,选择 2 等待 id 和文本。与您的 json 文件相同。如果您无论如何都必须这样做,请执行return { id: obj.id, text: obj.text };
  • @Camille 我对它没有任何特殊需要,这只是我能找到的唯一示例代码:(我不熟悉 javascript 或 jquery,所以我很迷茫这个。我可以通过将数据存储在 javascript var 中来修复它,但实际上应该使用 json 文件来完成。
  • 好的,删除函数processResults 以在ajax 中仅具有dataTypeurl 属性
  • @Camille 我发现了问题,json文件中的数据格式不正确。我的数据现在可以正确加载了。

标签: javascript json jquery-select2


【解决方案1】:

在@Camille 的帮助下找到了解决方案。

  1. 不必要地重新处理 json 文件(仅当您的 json 文件使用不同于 "id""text" 的标识符时才需要

  2. json文件格式不正确,见https://select2.org/data-sources/formats

代码:

// Create countries dropdown
$('#allowedCountries').select2({
    placeholder: 'Select allowed countries',
    selectOnClose: false,
    tags: false,
    tokenSeparators: [',', ' '],
    ajax: {
        dataType : "json",
        url      : "includes/countries.json",
    },
});

countries.json

{
    "results": [
    {
        "id": 1,
        "text": "Afghanistan"
    },
    {
        "id": 2,
        "text": "Aland Islands"
    },
    {
        "id": 3,
        "text": "Albania"
    },

...

    {
        "id": 245,
        "text": "Yemen"
    },
    {
        "id": 246,
        "text": "Zambia"
    },
    {
        "id": 247,
        "text": "Zimbabwe"
    }
    ]
}

【讨论】:

  • 不错!干得好:-)
猜你喜欢
  • 2013-08-28
  • 1970-01-01
  • 1970-01-01
  • 2016-10-28
  • 2011-11-12
  • 1970-01-01
  • 1970-01-01
  • 2015-12-04
相关资源
最近更新 更多