AJAX Select2 模板中的数据
AJAX data in template of Select2
我正在用 AJAX 数据填充 Select2。我的代码如下。
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,
});
我想在 templateSelection
的 formatState()
中获取 processResults
的 AJAX 数据 text[1]
。
我怎样才能得到它?
您可以通过 processResults
传递任何额外数据。在你的情况下它可以是
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
};
然后在templateSelection
中访问
if (!state.id) {
return state.text;
}
return $(`<span>${state.text} & ${state.text2}</span>`);
我正在用 AJAX 数据填充 Select2。我的代码如下。
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,
});
我想在 templateSelection
的 formatState()
中获取 processResults
的 AJAX 数据 text[1]
。
我怎样才能得到它?
您可以通过 processResults
传递任何额外数据。在你的情况下它可以是
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
};
然后在templateSelection
if (!state.id) {
return state.text;
}
return $(`<span>${state.text} & ${state.text2}</span>`);