无法让Select2 Geonames一起工作



我在一起使用select2和geonames时遇到麻烦。我可以生成一个城市列表,但不能选择任何作为选择选项。

html

<select id="cities" name= "cities">
  <option value="3620194" selected="selected">Choisir une ville</option>
</select>

JS

function formatRepo (repo) {
      if (repo.loading) return repo.text;
      var markup = "<div class='select2-result-repository clearfix'>" +
        "<div class='select2-result-repository__meta'>" +
            "<div class='select2-result-repository__title'>" + repo.toponymName + "</div>";
      return markup;
    }
    function formatRepoSelection (repo) {
      return repo.toponymName;
    }  
$(document).ready(function() {

    $( '#cities' ).select2({
        ajax: {
            url: "http://ws.geonames.org/searchJSON",
            dataType: "json",
            data: function (params) {
                return {
                    username:'xxx',
                    featureClass: "P",
                    style: "full",
                    q: params.term, // search term
                    page: params.page,
                    country: "CH"
                };
            },
            success: function(data) {
                console.log('Success!', data.geonames);
            },
            processResults: function (data, params) {
                // parse the results into the format expected by Select2
                // since we are using custom formatting functions we do not need to
                // alter the remote JSON data, except to indicate that infinite
                // scrolling can be used
                params.page = params.page || 1;
                return {
                    results: data.geonames,
                    pagination: {
                        more: (params.page * 30) < data.total_count
                    }
                };
            },
        },
        escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
        minimumInputLength: 1,
        templateResult: formatRepo,
        templateSelection: formatRepoSelection
    });
});

您可以在这里看到小提琴:[https://jsfiddle.net/rjvluof4/] [1]

有人知道为什么我不能选择城市吗?

经过数小时的反复试验,我能够解决这个问题。希望它能帮助任何人。

基本上,Select2必须在ProcessResults中接收ID和文本。

GeOnames给出" GeOnameId"one_answers" toponymname",您要做的就是映射它们以匹配ID和文字。

这是代码:

processResults: function (data) {
        data = $.map(data.geonames, function (obj) {
            obj.id = obj.id || obj.geonameId;
            obj.text = obj.text || obj.toponymName;
            return obj;
        });
      return {
        results: data,
      };
}

最新更新