exhtml
7/12/2017 - 9:48 AM

select2 load ajax remote data: https://select2.github.io/examples.html#data-ajax

<select class="js-example-data-ajax form-control">
  <!-- if you need to include a default selection <option value="3620194" selected="selected">select2/select2</option> -->
  <option value="">Select...</option>
</select>
var $ajax = $(".js-example-data-ajax");

$.fn.select2.defaults.set("width", "100%");

// ver original para mas detalles
function formatItem (item) {
  if (item.loading) return 'Searching...';
  return item.title
}

function formatItemSelection (item) {
  return item.title
}

$ajax.select2({
  ajax: {
    url: "https://jsonplaceholder.typicode.com/posts",
    dataType: 'json',
    delay: 250,
    data: function (params) {
      return {
        userId: params.term, // search term
        page: params.page
      };
    },
    processResults: function (data, params) {
      params.page = params.page || 1;

      return {
        //results: data.items,
        results: data,
        pagination: {
          more: (params.page * 30) < data.total_count
        }
      };
    },
    cache: true
  },
  escapeMarkup: function (markup) { return markup; },
  minimumInputLength: 1,
  templateResult: formatItem,
  templateSelection: formatItemSelection
});

// default settings for select2
$.fn.select2.defaults.set("width", "100%");

// ver ejemplo original del github de select2 para mas detalles de 
// como formatear de formas mas complejas
function formatRepo (repo) {
  if (repo.loading) return repo.text;
  var markup = "<div class='clearfix'>" + repo.full_name + "(" + repo.forks_count + ")</div>";
  return markup;
}

function formatRepoSelection (repo) {
  return repo.full_name || repo.text;
}

$(".js-example-data-ajax").select2({
  ajax: {
    url: "https://api.github.com/search/repositories",
    dataType: 'json',
    delay: 250,
    data: function (params) {
      return {
        q: params.term, // search term
        page: params.page
      };
    },
    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.items,
        pagination: {
          more: (params.page * 30) < data.total_count
        }
      };
    },
    cache: true
  },
  escapeMarkup: function (markup) { return markup; },
  minimumInputLength: 3,
  templateResult: formatRepo,
  templateSelection: formatRepoSelection
});