JSP 使用 AJAX 的级联下拉菜单

6ie5vjzr  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(158)

我想从数据库中的一个表创建两个级联下拉列表。
第一个下拉菜单是Main Category,它工作得很好,也就是说,它使用 AJAX 填充下拉菜单中的所有数据。
现在,第二个下拉列表子类别也被填充。但问题是,当我选择主类别时,它会获取第二个下拉列表中的整个子类别列。
我想要的是,如果我选择了一个主要类别,只有在数据库中该行的子类别应该填充,而不是整个列。
我会添加我的数据库表的屏幕截图,以便更好地理解,也我的代码,我已经尝试。

例如:-如果我在主类别中选择水果,则在子类别中只应填写aaaa。同样,如果我在主类别中选择蔬菜,则在子类别中只应填写bbbb。
但现在发生的是如果我选择水果,整个子类别列将被填充
能有人请帮助我关于这将是非常感谢,提前感谢。
我写的 AJAX 。

<script type="text/javascript">
    
        $(document).ready(function()
        {
            $.ajax
            ({
                url: "listdropdowns",
                type: "GET",
                dataType: "json",
                success: function(loadmaindropdown)
                {
                    var populatemain= $("#home_main_cat_dropdown_id");

                    $.each(loadmaindropdown, function(index, category)
                    {
                        $("<option>").val(category.main_category).text(category.main_category).appendTo(populatemain);
                    });
                },
            });
        });
        
        $(document).ready(function()
        {
            $("#home_main_cat_dropdown_id").change(function()
            {
                var main_category_values = (this.value) ;

            $.ajax
            ({
                url: "listdropdowns",
                type: "GET",
                dataType: "json",
                success: function(loadsubdropdown)
                {
                    var populatesub = $("#home_sub_cat_dropdown_id");

                    $.each(loadsubdropdown, function(index, category)
                    {
                        $("<option>").val(category.sub_category).text(category.sub_category).appendTo(populatesub);
            console.log(home_sub_cat_dropdown_id.value);                
                    });
                },
            });
            });
        });
        
    </script>

在我的DAO中,我从那里得到整个类别列表

public List<Category> selectAllCategory() throws SQLException, ClassNotFoundException
    {
        List<Category> listCategory = new ArrayList<>();
        
        Connection conn = DatabaseConnection.initializeDatabase();
        
        String query = " select * from list_of_categories ";
        
        try
        {
            PreparedStatement prestmt = conn.prepareStatement(query);
             
            ResultSet rs = prestmt.executeQuery();
             
             while (rs.next())
             {   
                 int id = rs.getInt("id");                           
                 String main_category = rs.getString("main_category");
                 String sub_category = rs.getString("sub_category");
       
                 listCategory.add(new Category(id,main_category,sub_category));
             }  
        }

我的控制器

public void populate_dropdowns(HttpServletRequest request, HttpServletResponse response)throws SQLException, IOException, ClassNotFoundException, ServletException, ParseException
    {
        try
        {
            List<Category> listCategory = productDAO.selectAllCategory();
            
            String json = new Gson().toJson(listCategory);
            
            response.setContentType("application/json");
            
            response.setCharacterEncoding("UTF-8");
            
            response.getWriter().write(json);
        }
        
        catch (SQLException e)
        {
            e.printStackTrace();
            throw new ServletException(e);
        }
    }
vom3gejh

vom3gejh1#

我修改了我的代码,如下面解决我的问题,现在它的工作正常。
我为DAO和Controller中的下拉菜单创建了单独的方法,并根据需要提取数据。
我的 AJAX 函数:-

<script type="text/javascript">

        $(document).ready(function()
        {
            $.get("listmaindropdown",function(loadmaindropdown)
            {
                var aaaa = $("#home_main_cat_dropdown_id");
                $.each(loadmaindropdown, function(index, category)
                {
                    $("<option>").val(category.main_category).text(category.main_category).appendTo(aaaa);
                });
                    
                $("#home_main_cat_dropdown_id").change(function()
                {
                    var main_category_values = (this.value);
    
                        $.get("listsubdropdown",function(loadsubdropdown)
                        {
                            var bbbb = $("#home_sub_cat_dropdown_id")
                                
                            bbbb.find('option').remove();
                                
                            $.each(loadsubdropdown, function(index, category)
                            {
                                if(main_category_values == category.main_category)
                                {
                                    $("<option>").val(category.sub_category).text(category.sub_category).appendTo(bbbb);
                                }
                            });  
                        });
                    }); 
                });
            });
        }   

    </script>

DAO:-

public List<Category> selectonlymaincategory() throws SQLException, ClassNotFoundException
    {
        List<Category> listCategory = new ArrayList<>();
        
        Connection conn = DatabaseConnection.initializeDatabase();
        
        String query = " select distinct main_category from list_of_categories order by main_category ";
        
        try
        {
            PreparedStatement prestmt = conn.prepareStatement(query);
             
            ResultSet rs = prestmt.executeQuery();
             
             while (rs.next())
             {                       
                 String main_category = rs.getString("main_category");

                 listCategory.add(new Category(main_category));
             }  
        } 
         
        catch (SQLException e) 
        {
            e.printStackTrace();
        }
        
        return listCategory;        
    }
    
    public List<Category> selectonlysubcategory() throws SQLException, ClassNotFoundException
    {
        List<Category> listCategory = new ArrayList<>();
        
        Connection conn = DatabaseConnection.initializeDatabase();
        
        String query = " select * from list_of_categories order by sub_category";
        
        try
        {
            PreparedStatement prestmt = conn.prepareStatement(query);
             
            ResultSet rs = prestmt.executeQuery();
             
             while (rs.next())
             {                       
                 int id = rs.getInt("id");                           
                 String main_category = rs.getString("main_category");
                 String sub_category = rs.getString("sub_category");

                 listCategory.add(new Category(id,main_category,sub_category));
             }  
        } 
         
        catch (SQLException e) 
        {
            e.printStackTrace();
        }
        
        return listCategory;        
    }

控制器Servlet:-

public void populate_maindropdown(HttpServletRequest request, HttpServletResponse response)throws SQLException, IOException, ClassNotFoundException, ServletException, ParseException
    {
        try
        {
            List<Category> listCategory = productDAO.selectonlymaincategory();
            
            String json = new Gson().toJson(listCategory);
            
            response.setContentType("application/json");
            
            response.setCharacterEncoding("UTF-8");
            
            response.getWriter().write(json);
        }
        
        catch (SQLException e)
        {
            e.printStackTrace();
            throw new ServletException(e);
        }
    }
    public void populate_subdropdown(HttpServletRequest request, HttpServletResponse response)throws SQLException, IOException, ClassNotFoundException, ServletException, ParseException
    {
        try
        {
            List<Category> listCategory = productDAO.selectonlysubcategory();
            
            String json = new Gson().toJson(listCategory);
            
            response.setContentType("application/json");
            
            response.setCharacterEncoding("UTF-8");
            
            response.getWriter().write(json);
        }
        
        catch (SQLException e)
        {
            e.printStackTrace();
            throw new ServletException(e);
        }
    }

相关问题