javascript - 使用 AJAX 在 HTML 下拉列表中显示 python 列表的值
问题描述
我正在使用 Django 和 AJAX 来实现链式下拉菜单。首先将提示用户从下拉列表中选择品牌名称,根据选择的品牌名称,该品牌制造的所有产品名称将显示在第二个下拉列表中。
视图.py
def chained_dropdown(request):
if request.method == "POST":
brand = request.POST['brand']
print(brand)
sort_by_brand = list(models.Product.objects.filter(brand=brand).order_by('product_id').values('product_id', 'product_name'))
data = {
'SortByBrand': sort_by_brand
}
return JsonResponse(data)
AJAX 请求:
var brand = $('#brand').val()
$.ajax({
type: "POST",
url: "/changeddropdown",
data:{
"brand": brand,
}, success: function (data){
// What should I do here?
console.log(data)
},
})
模板片段: 这是我希望显示产品名称的位置,选项值应该是它们对应的 product_id。
<label for="product_id"> Product ID</label>
<select name="product_id" id="product_id">
<option disabled selected="true"> --Select -- </option>
<option value=""> </option>
</select>
供您参考,这是console.log(data)
打印的内容:
{SortByBrand: [{product_id: 31, product_name: "Lotion"}, {product_id: 32, product_name: "Deo"}]}
我无法在模板中显示此信息,任何帮助将不胜感激。
解决方案
下面的代码应该可以工作
var brand = $('#brand').val()
$.ajax({
type: "POST",
url: "/changeddropdown",
data:{
"brand": brand,
}, success: function (data){
var select = document.getElementById("product_id");
//clear previous data
document.getElementById('product_id').innerText = null;
data.SortByBrand.forEach(function(element, index, list) {
var option = document.createElement('option');
option.text = element.product_name;
option.value = element.product_id
select.add(option, 0);
list[index] = {'name': element};
});
},
})
推荐阅读
- javascript - 关于 JS 类助手的最佳实践(课内或课外)?
- sqlite - 使用该列的唯一值从共享另一列的相同值的多个行子集中更新 1 列
- postgresql - 如何从多个级别的postgresql jsonb对象中提取数据
- bpmn - Camunda admin servlet 上下文菜单更改
- python - 使用 udfs 在 pyspark 数据框中提取一列
- python-3.x - 无法导入 spacy -Jupyter python 3 笔记本
- c# - 我的同步函数 hashCode 使用方法是否正确?
- notifications - 当我点击 nativescript-local-notifications 时,它会启动应用程序,但 addOnMessageReceivedCallback 不起作用
- virtual-machine - 从虚拟机/虚拟盒子浏览如何防止指纹或跟踪?
- python - py.checkio 解决 list 语法错误