我刚开始使用 [select2][1],我正在开发一个需要从 JSON 数据源填充的标签列表(如 StackOverflow 上)的项目。我正在使用在这个问题上找到的一个例子:[Tagging With Ajax In Select2][2] 但我在让它工作时遇到了一些麻烦。
// Testing JSON load
$("#testJsonLoad").select2({
tags: true,
tokenSeparators: [",", " "],
createSearchChoice: function (term, data) {
if ($(data).filter(function () {
return this.text.localeCompare(term) === 0;
}).length === 0) {
return {
id: term,
text: term
};
}
},
multiple: true,
ajax: {
url: 'data.json',
dataType: "json",
data: function (term, page) {
return {
q: term
};
},
results: function (data, page) {
return {
results: data
};
}
}
});
仅出于测试目的,data.json 页面中包含以下数据:
{
"data": [
{ "id" : 1, "text" : "Alabama" },
{ "id" : 2, "text" : "Alaska" },
{ "id" : 3, "text" : "Arizona" },
{ "id" : 4, "text" : "Arkansas" },
{ "id" : 5, "text" : "California" },
{ "id" : 6, "text" : "Colorado" },
{ "id" : 7, "text" : "Connecticut" },
{ "id" : 8, "text" : "Delaware" },
{ "id" : 9, "text" : "District of Columbia" },
{ "id" : 10, "text" : "Florida" },
{ "id" : 11, "text" : "Georgia" },
{ "id" : 12, "text" : "Hawaii" },
{ "id" : 13, "text" : "Idaho" } ]
}
我的问题是我收到了这个错误:this.text is undefined - Line 78
return this.text.localeCompare(term) === 0;
我认为这可能与我的 JSON 格式化方式有关。我尝试了几种不同的格式,但我的大部分在线研究都没有产生积极的结果。