发生什么事:
默认情况下,您在ajax.results中返回的对象的结果应该是此结构中的数组[{id:1,text:“a”},{id:2,text:“b”},…] 。
results: function (data, page) {
var array = data.results; //depends on your JSON
return { results: array };
}
* @param options.results a function(remoteData, pageNumber, query) that converts data returned form the remote request to the format expected by Select2.
* The expected format is an object containing the following keys:
* results array of objects that will be used as choices
* more (optional) boolean indicating whether there are more results available
* Example: {results:[{id:1, text:'Red'},{id:2, text:'Blue'}], more:true}
阅读源代码,我们可以看到ajax.results是调用AJAX的成功的:
success: function (data) {
// TODO - replace query.page with query so users have access to term, page, etc.
// added query as third paramter to keep backwards compatibility
var results = options.results(data, query.page, query);
query.callback(results);
}
所以ajax.results真的只是一个函数,您可以将数据格式化为适当的结构(例如[{id:a,text:“a”},{id:b,text:“b”},…] )在数据传递给query.callback之前:
callback: this.bind(function (data) {
// ignore a response if the select2 has been closed before it was received
if (!self.opened()) return;
self.opts.populateResults.call(this, results, data.results, {term: term, page: page, context:context});
self.postprocessResults(data, false, false);
if (data.more===true) {
more.detach().appendTo(results).html(self.opts.escapeMarkup(evaluate(self.opts.formatLoadMore, self.opts.element, page+1)));
window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
} else {
more.remove();
}
self.positionDropdown();
self.resultsPage = page;
self.context = data.context;
this.opts.element.trigger({ type: "select2-loaded", items: data });
})});
什么query.callback最终会做的是正确设置逻辑,以便当您选择其中一个项目并触发.selectChoice时,一切正常。
selectChoice: function (choice) {
var selected = this.container.find(".select2-search-choice-focus");
if (selected.length && choice && choice[0] == selected[0]) {
} else {
if (selected.length) {
this.opts.element.trigger("choice-deselected", selected);
}
selected.removeClass("select2-search-choice-focus");
if (choice && choice.length) {
this.close();
choice.addClass("select2-search-choice-focus");
this.opts.element.trigger("choice-selected", choice);
}
}
}
因此,如果在.selectChoice被调用之前导致类别.select2-search-choice-focus不被添加到DOM元素中,那么会发生一些配置错误(例如,结果不正确的结构)。
The drop-down popup stays open. Nothing gets put in the actual field. There are no errors in the JavaScript console. Its like I didn’t click anything.
解决方案
有很多解决方案。其中一个当然是在ajax.results中进行一些数组键操作。
results: function (data, page) {
//data = { results:[{ItemId:1,ItemText:"a"},{ItemId:2,ItemText:"b"}] };
var array = data.results;
var i = 0;
while(i < array.length){
array[i]["id"] = array[i]['ItemId'];
array[i]["text"] = array[i]['ItemText'];
delete array[i]["ItemId"];
delete array[i]["ItemText"];
i++;
}
return { results: array };
}
但是你可能会问:为什么id是“id”,文本是数组中的“text”?
[{id:1,text:"a"},{id:2,text:"b"}]
数组可以在这个结构中吗?
[{ItemId:1,ItemText:"a"},{ItemId:2,ItemText:"b"}]
答案是肯定的。您只需要使用自己的功能覆盖id和text函数。
以下是Select2.js中的.selecte2的原始功能:
id: function (e) { return e == undefined ? null : e.id; },
text: function (e) {
if (e && this.data && this.data.text) {
if ($.isFunction(this.data.text)) {
return this.data.text(e);
} else {
return e[this.data.text];
}
} else {
return e.text;
}
},
要覆盖它们,只需将您自己的函数添加到传递给的对象中.selecte2:
$('#mySelect').select2({
id: function (item) { return item.ItemId },
text: function (item) { return item.ItemText }
......
});
更新
还有什么事情呢
However, the text of the selected item does not appear in the field after the list closes.
这意味着.selectChoice已成功执行。现在的问题在于.updateSelection。在源代码中:
updateSelection: function (data) {
var container=this.selection.find(".select2-chosen"), formatted, cssClass;
this.selection.data("select2-data", data);
container.empty();
if (data !== null) {
formatted=this.opts.formatSelection(data, container, this.opts.escapeMarkup);
}
if (formatted !== undefined) {
container.append(formatted);
}
cssClass=this.opts.formatSelectionCssClass(data, container);
if (cssClass !== undefined) {
container.addClass(cssClass);
}
this.selection.removeClass("select2-default");
if (this.opts.allowClear && this.getPlaceholder() !== undefined) {
this.container.addClass("select2-allowclear");
}
}
从这里我们可以看到,在将相应的文本字符串放入输入之前,它将调用formatSelection。
formatSelection: function (data, container, escapeMarkup) {
return data ? escapeMarkup(this.text(data)) : undefined;
},
更新:解决方案
以前我以为this.text(data)可以通过在参数中具有文本:funcion(item){…}来覆盖,但遗憾的是它不会这样工作。
因此,为了在文本中正确显示文本,您应该通过执行来覆盖formatSelection
$('#mySelect').select2({
id: function (item) { return item.ItemId },
formatSelection: function (item) { return item.ItemText }
//......
});
而不是尝试覆盖文本(应该具有相同的效果,但是这种覆盖方式在库中尚未被支持/实现)
$('#mySelect').select2({
id: function (item) { return item.ItemId },
text: function (item) { return item.ItemText } //this will not work.
//......
});