【问题标题】:how do I sort response fetched from AJAX request and map them as <option> to <select> tag?如何对从 AJAX 请求中获取的响应进行排序并将它们作为 <option> 映射到 <select> 标记?
【发布时间】:2022-01-14 22:03:50
【问题描述】:

我正在尝试使用 AJAX 对从后端获取的响应进行排序。这是我的代码:

let $select = $("#colony_code");
  
$.ajax({
      url: 'backend.php',
      type: 'POST',
      data: { "input": "fetch_colony_codes" }, 
      dataType: 'json', 
      success: function(response) {
        let selectedValue = $select.val();
        let html = response.filter((e, i, a) => a.indexOf(e) === i).map(item => `<option value="${item}">${item}</option>`);
        $select.html(html).val(selectedValue);
      },
      complete: function() {}
});

现在,我希望将所有 options 排序到我的 &lt;select&gt; 标记中。如何对选项进行排序?

【问题讨论】:

    标签: jquery ajax


    【解决方案1】:

    伙计,我很愚蠢。只需在success(..) 的开头添加response.sort(); 即可解决我的问题。呵呵

    【讨论】:

    • 您应该考虑接受这一点,以便其他人可以看到您的问题已解决,尤其是如果您自己解决了问题:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-16
    • 1970-01-01
    • 2017-09-15
    • 1970-01-01
    • 2011-03-03
    • 2020-09-22
    相关资源
    最近更新 更多