使用AJAX在HTML下拉列表中显示python列表的值

2024-05-16 06:31:33 发布

您现在位置: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)
        },
    })

模板片段: 这是我想要显示产品名称的地方,选项值应该是它们对应的产品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"}]}

我在模板中显示此信息时遇到问题,如有任何帮助,将不胜感激


Tags: name名称id列表databyrequestajax
2条回答

下面的代码应该可以工作

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

    },
})

您必须在Ajax请求的成功回调中处理响应

$.ajax({
    type: "POST",
    url: "/changeddropdown",
    data:{
        "brand": brand,
    },
    success: function (data){
       console.log(data);

       // Add below snippet no
       let productSelectBox = $('#product_id');
       const productsData = data.SortByBrand;
       $.each(productsData, function(idx, product) {
           let productOption = $("<option/>", {
               value: product.product_id,
               text: product.product_name
           });
       
       productSelectBox.append(productOption);
       });
    }
});

Django的观点似乎奏效了。虽然,您可以通过使用Django REST框架来改进您的体系结构,但这不是这个问题的范围

相关问题 更多 >