【问题标题】:Transforming response data select2 do not working转换响应数据 select2 不起作用
【发布时间】:2018-10-12 13:49:18
【问题描述】:

我使用 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"}
]

【问题讨论】:

    标签: javascript jquery jquery-select2


    【解决方案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/

    【讨论】:

    • 谢谢@shyam-joshi,它的工作。问题是dataType: json,应该是dataType: jsonp
    猜你喜欢
    • 2016-04-02
    • 1970-01-01
    • 2021-04-26
    • 2020-10-05
    • 1970-01-01
    • 2015-07-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-02
    相关资源
    最近更新 更多