【问题标题】:how to loop the ajax response?如何循环ajax响应?
【发布时间】:2021-05-12 12:12:56
【问题描述】:

我正在尝试学习 AJAX 编码方式,并且刚刚开始使用 jquery。我想在单击(父)ie,选择标记后立即从 mongodb 数据库中获取子类别到选项标记。

在这里我尝试并获取了数据,但每个数据都在同一个选项标签中,我希望它们在不同的选项标签中。 这是jQuery代码

<script>
  $(function() {
    
    $('#subcategory-selector').on('click', function() {
      let $subCategory = $('#subCategory')
      let $category = $("#category").val()

      $.ajax({
        type: 'GET',
        url: '/getSubCategory/' + $category,
        success: function(data) {
          let result = [];
          for( let i = 0; i< data.subCategory.length; i++) {
            let obj = {
              id: data.subCategory[i]._id,
              subCategory: data.subCategory[i].subCategory,
            }
            result.push(obj)
          }
          
          $subCategory.append('<option>' + result[0].subCategory +'</option>')
          $subCategory.append('<option>' + result[1].subCategory +'</option>')
        },
        error: function() {
          alert("No sub Category found")
        }
      })
    })
  })
</script>

这里是html。 ** 在这个地方,我希望我的子类别在选项元素中。 **

               <div class="form-group">
                  <label class="form-control-label text-primary" for="example3cols2Input">Sub Category</label>
                  <select name="subCategory" id="subcategory-selector" class="form-control">
                    <option value="sub" id="subCategory"></option>
                  </select>
                </div>

我作为响应得到的 JSON 是:

{
  subCategory: [
    {
      category: [Array],
      _id: 609bb80061350f23301ba6b3,
      subCategory: 'hy',
      createdAt: 2021-05-12T11:12:00.035Z,
      updatedAt: 2021-05-12T11:12:00.035Z,
      __v: 0
    },
    {
      category: [Array],
      _id: 609bb80561350f23301ba6b4,
      subCategory: 'by',
      createdAt: 2021-05-12T11:12:05.886Z,
      updatedAt: 2021-05-12T11:12:05.886Z,
      __v: 0
    }
  ],
  _id: 609bb7e961350f23301ba6b2,
  category: 'Hello',
  image: 'images\\2021-05-12T11-11-37.489Z-images.jpg',
  createdAt: 2021-05-12T11:11:37.580Z,
  updatedAt: 2021-05-12T11:12:05.911Z,
  __v: 0
}

帮我在选项标签中渲染输出。

【问题讨论】:

  • 可能是因为你推送了result[0]result[1],而不是result[i]result[i+1],类似的东西。试试for( let result of data.subCategory) { $subCategory.append('&lt;option&gt;' + result.subCategory +'&lt;/option&gt;') }
  • 谢谢。我现在将结果保持在循环中。它正在工作
  • 很好,所以我发布了我的评论作为答案,如果它对您有用,请考虑将其标记为已接受。

标签: javascript jquery json ajax


【解决方案1】:

试试这个:

for( let result of data.subCategory) {
   $subCategory.append('<option>' + result.subCategory +'</option>')
}

【讨论】:

    猜你喜欢
    • 2016-07-04
    • 2020-07-02
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 2012-05-02
    • 2010-12-17
    • 2014-02-26
    • 1970-01-01
    相关资源
    最近更新 更多