我使用 select2 (v4) 并使用远程数据。响应是正确的,但 processResults 函数不会调用,并且 select2 不会显示任何内容。
$('#country').select2({
placeholder: 'Select a country',
minimumInputLength: 3,
ajax: {
url: 'https://battuta.medunes.net/api/country/search/?key=xx',
dataType: 'json',
processResults: function(data) {
var results = [];
$.each(data, function (index, country) {
results.push({
id: country.code,
text: country.name
});
});
return {
results: results
};
},
data: function(params) {
var query = {
country: params.term
}
return query;
}
},
width: 'resolve',
});
ajax 请求的响应示例:
[
{"name": "Indonesia", "code": "Id"},
{"name": "French Polynesia", "code": "pf"}
]
最佳答案
嗨,下面是它的选择代码
$('#country').select2({
placeholder: 'Select a country',
minimumInputLength: 3,
ajax: {
url: function(param){return 'https://battuta.medunes.net/api/country/search/'},
dataType: 'jsonp' ,
data: function (params) {
var query = {
country: params.term,
// callback :"?",
key:"00000000000000000000000000000000" //put your key here
}
//this is important to make sure no extra params are added becuase the api rejects anything that has wrong params
// Query parameters will be ?city=[term]&callback=?,key=
return query;
},
processResults: function(data) {
var results = [];
$.each(data, function (index, country) {
results.push({
id: country.code,
text: country.name
});
});
return {
"results":results
};
},
},
width: 'resolve',
});
这是我的 fiddle ,显示工作国家/地区搜索 https://jsfiddle.net/shyamjoshi/jbfrnqLd/37/
关于javascript - 转换响应数据 select2 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50134853/