按照教程Select2 with AJAX,我正在尝试使用ajax检索学生列表。我的意见是:
<select class="form-control" id="student_id" name="student_id"></select>
,脚本是:
var url = '';
url += "{{ route('api.student_list') }}";
console.log(url); //outputs http://localhost/project-child/public/api/get-students
$( "#student_id" ).select2({
placeholder: 'Select an item',
ajax: {
url: url,
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: data
};
},
cache: true
}
});
JSON响应类似于
[{"id":1,"text":"EJAJUL HAQUE"},{"id":2,"text":"MUSTAK AHMED"},{"id":3,"text":"AZAD HOQUE"},{"id":4,"text":"ANJARUL HAQUE"},{"id":5,"text":"ARIFUL ISLAM"},{"id":6,"text":"SANJITA KHATUN"},{"id":7,"text":"MARINA SULTANA"},{"id":8,"text":"SULTANA BEGUM"},{"id":9,"text":"SABINA KHATUN"},{"id":10,"text":"JENIFA AHMED"},{"id":11,"text":"REJUON AHMED"},{"id":12,"text":"FARITA KHATUN"},{"id":13,"text":"HABIJUL HOQUE"},{"id":14,"text":"JENIFA MUSKAN"},{"id":15,"text":"JOTUFA WAHID"},{"id":16,"text":"MAUSUMI BEGUM"},{"id":17,"text":"ABJARUL RAHMAN"},{"id":18,"text":"JANNATUR ANJU"},{"id":19,"text":"RIYAD "},{"id":20,"text":"RAJIBUL HOQUE"},{"id":21,"text":"UMME SALMA"},{"id":22,"text":"RAFIKUL ISLAM"},{"id":23,"text":"ABJAL HUSSAIN"},{"id":24,"text":"IMAM AHMED"},{"id":25,"text":"NARGIS SULTANA"},{"id":26,"text":"MAFUDA KHATUN"},{"id":27,"text":"SIDDIKUL NAHAR"},{"id":28,"text":"KHALEDA BEGUM"}]
但如果我搜索,说EJAJ它说没有找到结果。我正在使用精选版本4.0.3
答案 0 :(得分:0)
on processResults,计算数据,如果其长度== 0,则执行smt ...
processResults: function (data) {
if(data.length==0){
getFromGoogle();
}
return {
results: data
};
},
答案 1 :(得分:-1)
摆脱整个processResults
的东西,让你的数据服务器将你的JSON数组变成一个带有键results
的子数组。这样:
{"results":[your-JSON-array-above]}