转换响应数据select2不起作用

时间:2018-05-02 12:37:56

标签: javascript jquery jquery-select2

我使用select2(v4)并使用远程数据。响应是正确的,但processResults函数不调用而select2不显示任何内容。

 $('#country').select2({
     placeholder: 'Select a country',
     minimumInputLength: 3,
     ajax: {
         url: 'https://battuta.medunes.net/api/country/search/?key=xx',
         dataType: 'json',                        
         processResults: function(data) {
            var results = [];
            $.each(data, function (index, country) {
                 results.push({
                     id: country.code,
                     text: country.name
                 });
             });

             return {
                results: results
             };                            
         },                        
         data: function(params) {
            var query = {
               country: params.term
            }

            return query;
        }
     },
     width: 'resolve',
  }); 

来自ajax请求的示例响应:

[
  {"name": "Indonesia", "code": "Id"}, 
  {"name": "French Polynesia", "code": "pf"}
]

1 个答案:

答案 0 :(得分:1)

下面是下面的选择代码

$('#country').select2({
     placeholder: 'Select a country',
     minimumInputLength: 3,
     ajax: {
         url: function(param){return 'https://battuta.medunes.net/api/country/search/'},
         dataType: 'jsonp' ,
         data: function (params) {


      var query = {
       country: params.term,
      // callback :"?",
       key:"00000000000000000000000000000000" //put your key here 
      }
//this is important to make sure no extra params are added becuase the api rejects anything that has wrong params
      // Query parameters will be ?city=[term]&callback=?,key=
      return query;
    },
          processResults: function(data) {
            var results = []; 
            $.each(data, function (index, country) {
                 results.push({
                     id: country.code,
                     text: country.name
                 });
             });

             return {
              "results":results
             };                            
         },

     },

     width: 'resolve',
  }); 

这是我的小提示,显示了工作国家搜索https://jsfiddle.net/shyamjoshi/jbfrnqLd/37/