怎么了:
默认情况下,results
您要返回的对象的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 };
}
In Select2.js https://github.com/ivaynberg/select2/blob/master/select2.js它实际上指出:
* @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);
}
So 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);
}
}
}
因此,如果存在一些配置错误(例如results
结构不正确)导致该类.select2-search-choice-focus
之前不要添加到 DOM 元素.selectChoice
被调用,这就是发生的事情:
下拉弹出窗口保持打开状态。没有任何内容被放入实际字段中。 JavaScript 控制台中没有错误。就像我没有点击任何东西一样。
解决方案
对此有很多解决方案。其中之一当然是在中进行一些数组键操作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必须是“text”?
[{id:1,text:"a"},{id:2,text:"b"}]
数组可以用这个结构吗?
[{ItemId:1,ItemText:"a"},{ItemId:2,ItemText:"b"}]
答案是肯定的。你只需要覆盖id
and text
具有您自己的功能的功能。
以下是原始函数.selecte2
in Select2.js https://github.com/ivaynberg/select2/blob/master/select2.js:
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 }
......
});
Updates
还发生了什么:
但是,列表关闭后,所选项目的文本不会出现在字段中。
这意味着.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)
可以被覆盖text: funcion(item){ ... }
在参数中,但遗憾的是它不是这样工作的。
因此,要在字段中正确呈现文本,您应该覆盖formatSelection
通过做
$('#mySelect').select2({
id: function (item) { return item.ItemId },
formatSelection: function (item) { return item.ItemText }
//......
});
而不是尝试覆盖text
(据说应该具有相同的效果,但库中尚未支持/实现这种覆盖方式)
$('#mySelect').select2({
id: function (item) { return item.ItemId },
text: function (item) { return item.ItemText } //this will not work.
//......
});