我有一个select2选择菜单工作(从远程geobytes状态),但我不能选择具有相同索引ID的选项。例如,如果我搜索“新”,我会得到一些选项,我可以选择第一个选项New Albany,IN。然后,如果我键入“far”,第一个选项是Far Hills,NJ。当我选择它时,它会显示具有索引1的Albany,IN。
我尝试了加载远程数据的示例https://select2.github.io/examples.html#data-ajax。它的行为方式不一样,所以我想知道我是否错误地解析了我的结果。每次搜索时都会返回一个索引从1开始的新对象。
$('#input_3_4').select2({
ajax: {
url: "http://gd.geobytes.com/AutoCompleteCity?callback=?&template=%3Cgeobytes%20city%3E,%20%3Cgeobytes%20code%3E&filter=US",
dataType: 'json',
quietMillis: 1500,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
for(var i = 0; i < data.length; i++){
data[i] = {id:i+1, text:data[i]};
}
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
console.log(data);
return {
results: data,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true,
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 3,
//templateResult: formatRepo, // omitted for brevity, see the source of this page
//templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});
答案 0 :(得分:0)
var dataIndex = 1; //<<=====HERE
//select2 state selector with geobytes remote data source
$('#input_3_4').select2({
ajax: {
url: "http://gd.geobytes.com/AutoCompleteCity?callback=?&template=%3Cgeobytes%20city%3E,%20%3Cgeobytes%20code%3E&filter=US",
dataType: 'json',
quietMillis: 1500,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
for(var i = 0; i < data.length; i++){
data[i] = {id:dataIndex, text:data[i]}; //<<=====HERE
dataIndex++; //<<=====HERE
}
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
console.log(data);
return {
results: data,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true,
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 3,
//templateResult: formatRepo, // omitted for brevity, see the source of this page
//templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});