Je tente de faire un appel AJAX avec le plugin Select2 jQuery. La requête semble fonctionner, mais le problème se produit lorsque .results()
est appelé sur l’object options
:
Uncaught TypeError: options.results is not a function
Voici mon HTML:
Voici mon JS:
$(document).ready(function() { $('#topic_relation_source_topic_id').select2({ minimumInputLength: 3, ajax: { url: "", dataType: 'json', delay: 250, data: function (term, page) { return { q: term, //search term page_limit: 30, // page size page: page, // page number }; }, processResults: function (data, page) { var more = (page * 30) < data.total; return {results: data.topics, more: more}; } }, formatResult: topicFormatResult, formatSelection: formatRepoSelection, escapeMarkup: function (m) { return m; } }); function topicFormatResult(topic) { return topic.name } function formatRepoSelection(topic) { return '' + topic.name + '' } });
Voici le JSON retourné:
{"total":2, "topics":[{"id":305,"name":"Educational Assessment, Testing, And Measurement"},{"id":3080,"name":"Inspectors, Testers, Sorters, Samplers, And Weighers"}]}
Voici le code qui échoue:
function ajax(options) { var timeout, // current scheduled but not yet executed request handler = null, quietMillis = options.quietMillis || 100, ajaxUrl = options.url, self = this; return function (query) { window.clearTimeout(timeout); timeout = window.setTimeout(function () { var data = options.data, // ajax data function url = ajaxUrl, // ajax url ssortingng or function transport = options.transport || $.fn.select2.ajaxDefaults.transport, // deprecated - to be removed in 4.0 - use params instead deprecated = { type: options.type || 'GET', // set type of request (GET or POST) cache: options.cache || false, jsonpCallback: options.jsonpCallback||undefined, dataType: options.dataType||"json" }, params = $.extend({}, $.fn.select2.ajaxDefaults.params, deprecated); data = data ? data.call(self, query.term, query.page, query.context) : null; url = (typeof url === 'function') ? url.call(self, query.term, query.page, query.context) : url; if (handler && typeof handler.abort === "function") { handler.abort(); } if (options.params) { if ($.isFunction(options.params)) { $.extend(params, options.params.call(self)); } else { $.extend(params, options.params); } } $.extend(params, { url: url, dataType: options.dataType, data: data, success: function (data) { ========> var results = options.results(data, query.page, query); <========== query.callback(results); }, error: function(jqXHR, textStatus, errorThrown){ var results = { hasError: true, jqXHR: jqXHR, textStatus: textStatus, errorThrown: errorThrown }; query.callback(results); } }); handler = transport.call(self, params); }, quietMillis); }; }
Comme le plugin appelle results()
, vous devez également déclarer results: function (data, page)
au lieu de processResults: function (data, page)
.