How to use Select2 with JSON via Ajax request?

后端 未结 8 1884
遥遥无期
遥遥无期 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:26

    Here I give you my example which contain --> Country flag, City, State, Country.

    Here is my output.

    Attach these two Cdn js or links.

    
    
    

    js script

    //for apend flag of country.
    
    function formatState (state) {
        console.log(state);
        if (!state.id) {
          return state.text;
        }
        var baseUrl = "admin/images/flags";
        var $state = $(
          ' ' +state.text+ ''
        );
        return $state;
      };
    
    
    $(function(){
        $("#itemSearch").select2({
        minimumInputLength: 2,
        templateResult: formatState, //this is for append country flag.
        ajax: {
            url: URL,
            dataType: 'json',
            type: "POST",
            data: function (term) {
                return {
                    term: term
                };
            },
            processResults: function (data) {
                return {
                    results: $.map(data, function (item) {
                        return {
                            text: item.name+', '+item.state.name+', '+item.state.coutry.name,
                            id: item.id,
                            contryflage:item.state.coutry.sortname
                        }
                    })
                };
            }
    
        }
    });
    

    Expected JSON response.

    [
       {
          "id":7570,
          "name":"Brussels",
          "state":{
             "name":"Brabant",
             "coutry":{
                "sortname":"BE",
                "name":"Belgium",
    
             }
          }
       },
       {
          "id":7575,
          "name":"Brussels",
          "state":{
             "name":"Brabant Wallon",
             "coutry":{
                "sortname":"BE",
                "name":"Belgium",
    
             }
          }
       },
       {
          "id":7578,
          "name":"Brussel",
          "state":{
             "name":"Brussel",
             "coutry":{
                "sortname":"BE",
                "name":"Belgium",
    
             }
          }
       },
    
    ]
    

提交回复
热议问题