我 Select 了2在进行AJAX调用后显示数据.
<script>
$(document).ready(function () {
$("#citySelect").select2({
theme: 'bootstrap-5',
placeholder: "Search for your city",
dropdownAutoWidth: true,
width: 'auto',
minimumInputLength: 3,
allowClear: true,
async: true,
ajax: {
url:
function (params) {
return '@GatewaySettings.Value.Url' + '/api/location/cities/' + params.term;
},
contentType: "application/json; charset=utf-8",
type: 'GET',
processResults: function (result) {
return {
results: $.map(result, function (item) {
return { id: item.id, text: item.city };
}),
};
}
}
});
});
</script>
我能搜索到一份城市列表
我希望主动搜索结果显示为城市+‘,’+州+‘+邮政编码(例如,洛杉矶,加利福尼亚州90001),并在 Select 后只显示城市(即洛杉矶).
我正在try 按照文档进行操作,但总是得到一个未定义的结果.
Here is the output from the console
我只是不知道如何使用templating.
<script>
$(document).ready(function () {
$("#citySelect").select2({
theme: 'bootstrap-5',
placeholder: "Search for your city",
dropdownAutoWidth: true,
width: 'auto',
minimumInputLength: 3,
allowClear: true,
async: true,
templateResult: function (item) {
console.log(item);
return item.city + ', ' + item.state + ' ' + item.zip;
},
templateSelection: function (item) {
return item.city
},
ajax: {
url:
function (params) {
return '@GatewaySettings.Value.Url' + '/api/location/cities/' + params.term;
},
contentType: "application/json; charset=utf-8",
type: 'GET',
cache: true,
processResults: function (result) {
return {
results: $.map(result, function (item) {
return { id: item.id, text: item.city };
}),
};
}
}
});
});
</script>
如有任何帮助,欢迎光临
添加后来自控制台的结果
console.log("RESULTS", JSON.stringify(result, null, 2));
RESULTS [
{
"id": 5039,
"city": "Chandlers Valley",
"state": "Pennsylvania",
"zip": null
},
{
"id": 14327,
"city": "Chandlersville",
"state": "Ohio",
"zip": null
},
{
"id": 15915,
"city": "Chandler",
"state": "Indiana",
"zip": null
},
{
"id": 19293,
"city": "Chandler",
"state": "Minnesota",
"zip": null
},
{
"id": 22001,
"city": "Chandlerville",
"state": "Illinois",
"zip": null
},
{
"id": 26294,
"city": "Chandler",
"state": "Oklahoma",
"zip": null
},
{
"id": 26686,
"city": "Chandler",
"state": "Texas",
"zip": null
},
{
"id": 29715,
"city": "Chandler",
"state": "Arizona",
"zip": null
},
{
"id": 29716,
"city": "Chandler",
"state": "Arizona",
"zip": null
},
{
"id": 29717,
"city": "Chandler",
"state": "Arizona",
"zip": null
}
]