How to use Select2 with JSON via Ajax request?

后端 未结 8 1735
遥遥无期
遥遥无期 2020-11-29 15:58

My Select2 3.4.5 is not working with JSON data.

Here is my input box on HTML:



        
相关标签:
8条回答
  • 2020-11-29 16:45

    Here you have an example

    $("#profiles-thread").select2({
        minimumInputLength: 2,
        tags: [],
        ajax: {
            url: URL,
            dataType: 'json',
            type: "GET",
            quietMillis: 50,
            data: function (term) {
                return {
                    term: term
                };
            },
            results: function (data) {
                return {
                    results: $.map(data, function (item) {
                        return {
                            text: item.completeName,
                            slug: item.slug,
                            id: item.id
                        }
                    })
                };
            }
        }
    });
    

    It's quite easy

    0 讨论(0)
  • 2020-11-29 16:49

    In Version 4.0.2 slightly different Just in processResults and in result :

        processResults: function (data) {
            return {
                results: $.map(data.items, function (item) {
                    return {
                        text: item.tag_value,
                        id: item.tag_id
                    }
                })
            };
        }
    

    You must add data.items in result. items is Json name :

    {
      "items": [
        {"id": 1,"name": "Tetris","full_name": "s9xie/hed"},
        {"id": 2,"name": "Tetrisf","full_name": "s9xie/hed"}
      ]
    }
    
    0 讨论(0)
提交回复
热议问题