抱歉,但无法找到解决方法。
每当我尝试进行一些搜索时,select2将显示“结果无法加载”。
我认为我的ajax设置错误
HTML:
<select class="js-data-example-ajax form-control" multiple="multiple"></select>
脚本:
$(".js-data-example-ajax").select2({
ajax: {
url: '@Url.Action("LoadCity", "Addresses")',
dataType: 'jsonp',
delay: 250,
data: function(params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function(data) {
return {
results: data
};
},
cache: true
},
minimumInputLength: 1,
});
ADD 08.07.2016
一些更改ajax设置:
dataType: 'jsonp'
到
dataType: 'json'
并添加
type: 'GET',
现在没有消息'无法加载结果',也没有结果
答案 0 :(得分:0)
根据你最后的评论。处理结果应该返回一个具有结果键的对象。
所以它应该是:
return {
results: [{id: 1, text: 'Test'}]
}
答案 1 :(得分:0)
我最近在使用版本 4.0.5
时遇到了完全相同的问题这是从版本 4.0.6
开始解决的组件中的一个已知错误。从Github官方存储库:
修复AJAX数据源错误#4356
更新我的select2组件的本地版本可以解决此问题。
答案 2 :(得分:0)
我有这个工作的select2,我昨天实现了它,可能会对您有帮助。
select2_common('.accounts','Account & Description');
function select2_common(selector,placeholder)
{
$(selector).select2({
minimumInputLength:2,
placeholder:placeholder,
ajax: {
url: "your_url_here",
dataType: "json",
delay: 200,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data) {
// console.log(data);
return {
results: $.map(data, function(obj) {
if(obj.id!=0){
// console.log(obj);
return { id: obj.id, text: obj.name };
}
else
{return {id: obj.id, text: obj.name}}
})
};
},
cache: true
},
debug:false
});
}
//And your result should be in this form, from your method....
//I am using laravel php framework.
public function getAccountDetail(Request $request)
{
$q = $request->input('q');
$result=[];
if (isset($q) && $q != '') {
/*---------- Search by account code or title ----------*/
$data = DB::table('acc_accounts')->select('acc_id','acc_code','acc_title')
->where('acc_code', 'like', '%' . $q . '%')
->orWhere('acc_title', 'like', '%' . $q . '%')
->limit(10)->orderBy('acc_code')->get();
foreach ($data as $key => $value) {
$new1 = array('id' => $value->acc_id, 'name' => $value->acc_code.' ('.$value->acc_title.')' );
array_push($result,$new1);
}
print(json_encode($result));
}
}