Jquery 选择2使用JSON标记
我刚刚开始使用[select2][1],我正在处理一个需要从JSON数据源填充的标记列表(如StackOverflow)的项目。我正在使用一个关于这个问题的示例:[在Select2中使用Ajax进行标记][2],但我在让它工作时遇到了一些问题Jquery 选择2使用JSON标记,jquery,json,jquery-select2,Jquery,Json,Jquery Select2,我刚刚开始使用[select2][1],我正在处理一个需要从JSON数据源填充的标记列表(如StackOverflow)的项目。我正在使用一个关于这个问题的示例:[在Select2中使用Ajax进行标记][2],但我在让它工作时遇到了一些问题 // Testing JSON load $("#testJsonLoad").select2({ tags: true, tokenSeparators: [",", " "
// 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" } ]
}
我的问题是我遇到了以下错误:
此.text未定义-第78行
return this.text.localeCompare(term) === 0;
我想这可能与我的JSON格式有关。我尝试了几种不同的形式,但我在网上的大部分研究都没有产生积极的结果 将调试器放在if($(数据)之前。筛选(函数()并检查$(数据)中的内容。我发现了问题。我需要在results ajax函数中调用data.data(在我的示例中) 例如:
results: function (data, page) {
return {
results: data.data
};
}
结果需要json中的id和text节点,您可以告诉json使用这些节点名称输出结果,或者指定在JS中使用的节点: 现场示例:
query: function (query) {
var data = {results: []}, i, j, s;
for (i = 1; i < 5; i++) {
s = "";
for (j = 0; j < i; j++) {s = s + query.term;}
data.results.push({id: query.term + i, text: s});
}
query.callback(data);
}
query:函数(查询){
var data={results:[]},i,j,s;
对于(i=1;i<5;i++){
s=“”;
对于(j=0;j
Mine返回:[Object{tag={name=“name of tag”}]
这是无效的JSON。它应该是:{tag:{name:{name:{name of tag”}}很抱歉,这只是Firebug报告/格式化输出的格式。JSON实际上是正确的,请参阅我的答案…您的JSON看起来像什么?id和文本为我修复了它。谢谢!