如何循环ajax响应?

时间:2021-05-12 12:12:56

标签: javascript jquery json ajax

我正在尝试学习 AJAX 编码方式,并且刚刚开始使用 jquery。我想在点击(父)ie、select 标签后立即从 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。 ** 在这个地方,我希望我的子类别位于 option 元素中。 **

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

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

1 个答案:

答案 0 :(得分:1)

试试这个:

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