代码之家  ›  专栏  ›  技术社区  ›  d.abyss

选择2从本地json文件加载数据

  •  2
  • d.abyss  · 技术社区  · 8 年前

    我已经设置了select2,并使用JS变量加载到数据中,但是由于我的数据有很多选项(国家),我希望从加载它们,而不是在我的JS中。

    我创造了一个国家。包含所有国家的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 };
                    })
                };
            }
        },
    });
    

    国家。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'}]
    
    1 回复  |  直到 8 年前
        1
  •  3
  •   d.abyss    8 年前

    在@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",
        },
    });
    

    国家。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"
        }
        ]
    }