我有select2显示数据后,使一个afternoon调用。
<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)和选择后显示只是城市(即洛杉矶)。
我试图遵循文档,但我一直得到一个未定义的结果。
的数据
下面是控制台
的输出
我只是不知道如何使用模板。
<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
}
]
型
1条答案
按热度按时间mspsb9vt1#
您的
$.map()
在很大程度上是冗余的,并且还排除了您似乎想要使用的属性。您真正需要做的就是将数组嵌套在
results
属性下,以便Select2可以使用它。字符串
关于
ajax
属性的一些说明...GET
cache
属性为true
contentType