您好,我迷路了如何從下拉串列中呼叫 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>
這是我使用ajax的api
$.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"
}
]
我的下拉串列是可回收物和服務充電器的價格
我該怎么做 ?
uj5u.com熱心網友回復:
如果我理解正確,您希望將 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>然后將整個內容附加到<select>后面。盡管在有很多選項的情況下,您可能想要重新考慮使用簡單<select>的方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/386016.html
標籤:javascript html 阿贾克斯
