javascript Select2 不通过 AJAX 获取数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16101892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select2 not getting data via AJAX
提问by Cameron
I have the following code which should be getting data via AJAX using Select2
我有以下代码应该使用 Select2 通过 AJAX 获取数据
$('#Organisation').select2({
ajax: {
url: AppURL + 'Organisations/Manage/SearchByName/',
dataType: 'json',
quietMillis: 100,
data: function (term) {
return {
term: term
};
},
results: function (data) {
return {
results: data
};
}
}
});
If I look at the request using Web Inspector when searching 'O' I get:
如果我在搜索“O”时使用 Web Inspector 查看请求,我会得到:
[{"label":"Organisation 1","ID":2},{"label":"Organisation 2","ID":1}]
Any ideas what I'm doing wrong? I'd presume something incorrect in the results function.
任何想法我做错了什么?我认为结果函数中有一些不正确的东西。
The error I get is: Uncaught TypeError: Cannot call method 'toUpperCase' of undefined
我得到的错误是: Uncaught TypeError: Cannot call method 'toUpperCase' of undefined
回答by Arun P Johny
Try
尝试
$('#Organisation').select2({
ajax: {
url: 'data.json',
dataType: 'json',
quietMillis: 100,
data: function (term) {
return {
term: term
};
},
results: function (data) {
var results = [];
$.each(data, function(index, item){
results.push({
id: item.ID,
text: item.label
});
});
return {
results: results
};
}
}
});
Demo: Plunker
演示:Plunker
回答by Afnan Bashir
Other than above solution you can do one thing, instead of returning following json
除了上述解决方案,您可以做一件事,而不是返回以下 json
[{"label":"Organisation 1","ID":2},{"label":"Organisation 2","ID":1}]
[{"label":"Organisation 1","ID":2},{"label":"Organisation 2","ID":1}]
return this
返回这个
[{"text":"Organisation 1","id":2},{"text":"Organisation 2","id":1}]
[{"text":"Organisation 1","id":2},{"text":"Organisation 2","id":1}]
faced the same problem and figured this out after looking at few solutions proposed by other.
遇到了同样的问题,并在查看了其他人提出的一些解决方案后弄清楚了这一点。