【问题标题】:Cascading Dropdown Using Ajax and Web Api使用 Ajax 和 Web Api 级联下拉菜单
【发布时间】:2020-04-27 12:56:09
【问题描述】:

这是我的浏览器扩展对我的 web api 进行的 ajax 调用:

$(document).ready(function () {
    $select = $('#brandDropdownList');
    $.ajax({
        type: "GET",
        url: 'http://localhost:44358/api/brands',
        dataType: 'JSON',
        success:function(data) {
            $select.html('');
            $.each(data, function(key, val) {
                $select.append('<option id="' + val.brand_id + '">' + val.brand_name + '</option>');
            })
        },
        error: function(){
            $select.html('<option id="-2">Please try again...</option>');
        }
    }); 

这当前调用了我的 API,它返回一个 JSON 数组,然后我将每个项目修改为一个标签,从而进行下拉。然后我有另一个下拉列表,这将取决于用户选择的品牌名称。如何对我的 Web API 进行另一个 ajax 调用,该调用将根据品牌(特别是brand_id)填充另一个下拉列表,以便只显示所选品牌的产品。我已经创建了 web api 控制器,我目前正在通过我的 localhost 使用 URL 'http://localhost:44358/api/products' 访问它。

【问题讨论】:

    标签: jquery json ajax api


    【解决方案1】:

    您可以使用品牌下拉菜单中的on change event来获取其产品列表。

    $(document).ready(function () {
        $select = $('#brandDropdownList');
        $.ajax({
            type: "GET",
            url: 'http://localhost:44358/api/brands',
            dataType: 'JSON',
            success:function(data) {
                $select.html('<option value="">Select brand</option>');
                $.each(data, function(key, val) {
                    $select.append('<option value="' + val.brand_id + '">' + val.brand_name + '</option>');
                })
            },
            error: function(){
                $select.html('<option value="-2">Please try again...</option>');
        });
        //When user select any Brand below change event will callled. 
        $('#brandDropdownList').change(function (){
             var brand_id = $(this).val();
             getProducts(brand_id);
        }):
    
        function getProducts(brand_id){
              $select = $('#productDropdownList')
              $select.html('<option value="">Please wait...</option>');
              $.ajax({
                 type: "GET",
                 url: 'http://localhost:44358/api/products',
                 data:{brand_id : brand_id} //pass brand id to server to filter product of selected brand
                 dataType: 'JSON',
                 success:function(data) {
                     $select.html('');
                     $.each(data, function(key, val) {
                        $select.append('<option value="' + val.product_id + '">' + val.product_me + '</option>');
                     })
                 },
                 error: function(){
                     $select.html('<option value="-2">Please try again...</option>');
              });
        }
    });
    

    【讨论】:

    • 感谢您的帮助。我知道我必须使用 on change 事件,但不确定如何在下一次 Ajax 调用中传递品牌。非常感谢
    猜你喜欢
    • 2022-07-28
    • 1970-01-01
    • 1970-01-01
    • 2012-07-26
    • 1970-01-01
    • 2012-01-06
    • 2018-01-19
    • 1970-01-01
    • 2014-03-20
    相关资源
    最近更新 更多