【问题标题】:Dropdown call api from ajax来自ajax的下拉调用api
【发布时间】:2022-01-19 13:51:01
【问题描述】:

你好,我迷路了如何从我的下拉列表中调用 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"
    }
]

我的下拉菜单是按可回收物品和服务充电器定价

我该怎么做?

【问题讨论】:

  • 您只是在寻找a change event 处理程序吗?或者您是否尝试使用来自 AJAX 响应的值填充您的 &lt;select&gt;?我不太清楚你在问什么。
  • 嗨,我认为这是一个选择选项

标签: javascript html ajax


【解决方案1】:

如果我理解正确,您希望将 AJAX 结果作为&lt;option&gt; 元素添加到您的&lt;select&gt;。在您的 AJAX 成功处理程序中,只需遍历结果数组并将每个元素添加为 &lt;option&gt;。例如:

success: function(data) {
    for (let option of data) {
        $('#select-price-mode').append($('<option>', {
            value: option.PriceMode,
            text: option.PriceMode
        }));
    }
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-08
    • 1970-01-01
    • 2020-09-22
    • 2014-01-25
    • 2020-01-24
    • 2014-03-19
    相关资源
    最近更新 更多