来自 ajax 的下拉调用 api

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
        }));
    }
}

警告:如果您有 许多 选项,那么这可能会降低性能。在这种情况下,最好构建一个 <options> 的大 HTML 字符串,然后将整个字符串附加到 <select> 中。尽管在有 多个 选项的情况下,您可能还是想重新考虑使用简单的 <select>