javascript - 如何循环ajax响应?
问题描述
我正在尝试学习 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
}
帮助我在选项标签中呈现输出。
解决方案
尝试这个 :
for( let result of data.subCategory) {
$subCategory.append('<option>' + result.subCategory +'</option>')
}
推荐阅读
- css - 表格的垂直拉伸,不移动其内容
- swiftui - SwiftUI ScrollView 中包装的非滚动 UITextView 的内在高度
- python - re.findall 在 python 的列表中
- swiftui - 如何使用 SwiftUI 在 GoogleMaps 中创建多个标记?
- c++ - 我需要做什么才能使用此 BFS 代码显示最短路径?
- flutter - 根据屏幕大小控制元素大小
- php - 有没有办法从下面的代码中获取 account_name 值并解析为 json
- python - 如果具有相似的模式,Python 正则表达式会捕获该组
- c# - 如何设置标题内容-tye“text/xml;charset=utf-8”soap请求
- mysql - 需要帮助查找数字在查询结果中重复的次数