[英]Dropdown call api from ajax
你好我迷路了我怎么能从我的下拉列表中调用 api
这是 html 代码
<div class="col">
<label for="text4" class="col-form-label">Price Mode</label>
<select class="custom-select custom-select-sm col-10" id="select-price-mode">
<option value=""></option>
</select>
</div>
这是我的 api 使用 ajax
$.ajax({
// The url that you're going to post
/*
This is the url that you're going to put to call the
backend api,
in this case, it's
https://ecoexchange.dscloud.me:8080/api/get (production env)
*/
url:"https://ecoexchange.dscloud.me:8080/api/get",
// The HTTP method that you're planning to use
// i.e. GET, POST, PUT, DELETE
// In this case it's a get method, so we'll use GET
method:"GET",
// In this case, we are going to use headers as
headers:{
// The query you're planning to call
// i.e. <query> can be UserGet(0), RecyclableGet(0), etc.
query:"<query>",
// Gets the apikey from the sessionStorage
apikey:sessionStorage.getItem("apikey")
},
success:function(data,textStatus,xhr) {
console.log(data);
},
error:function(xhr,textStatus,err) {
console.log(err);
}
});
这是我的 json 响应
[
{
"PriceMode": "Price By Recyclables"
},
{
"PriceMode": "Service Charger"
}
]
我的下拉菜单是按可回收物品和服务充电器定价
我该怎么做?
如果我理解正确,您希望将您的 AJAX 结果作为<option>
元素添加到您的<select>
中。 在您的 AJAX 成功处理程序中,只需遍历结果数组并将每个元素添加为<option>
。 例如:
success: function(data) {
for (let option of data) {
$('#select-price-mode').append($('<option>', {
value: option.PriceMode,
text: option.PriceMode
}));
}
}
警告:如果您有很多选择,那么这可能会降低性能。 在这种情况下,最好构建一个大的 HTML 字符串<options>
和 append 整个事情到<select>
之后。 尽管在有很多选项的情况下,您可能还是想重新考虑使用简单的<select>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.