Estoy llenando Select2 con datos AJAX. Mi código es como a continuación.
function formatState(state) { if (!state.id) { return state.text; } var output = $('<span></span>'); // I would like get data `text[1]` of `processResults` here. return output; }; //more code here cellEle.html(`<select multiple="multiple"></select>`); let selectEle = cellEle.children("select").select2({ //more code here ajax: { //more code here processResults: function (data) { var options = []; if (data) { $.each(data, function (index, text) { options.push({ id: index, text: text[0]}); }); } return { results: options, more: false }; }, }, templateSelection: formatState, }); Me gustaría obtener el text[1] de processResults dentro de formatState() de templateSelection .
Cómo puedo obtenerlo ?
Puede pasar cualquier dato adicional a través de processResults . En tu caso puede ser
var options = []; if (data) { $.each(data.items, function (index, text) { options.push({ id: index, text: text[0], text2: text[1] /* <-- extra data */}); }); } return { results: options, more: false }; Luego acceda a él en templateSelection
if (!state.id) { return state.text; } return $(`<span>${state.text} & ${state.text2}</span>`);