[JSP] 第二個下拉選單依照第一個下拉選單的值更動

  • 12300
  • 0
  • AJAX
  • 2011-11-27

[JSP] 第二個下拉選單依照第一個下拉選單的值更動

ASP.net的DropDownList控制項有AutoPostBack搭配SelectedIndexChanged事件就可以很輕易辦到

但在JSP,如果第一個下拉選單onChange後,整個form去submit的話,畫面上的<input type=’text’ value=’word’ />文字就會被清掉

這時候就要使用jQuery+Ajax方法來做

<%@page import="System.Data.DataRow"%>
<%@page import="System.Data.DataTable"%>
<%@page import="DAL.DBUtil"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script src="js/jquery-1.4.1.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            function getProducts(categoryID)
            {
                var url="showProducts.jsp";
                jQuery.post(url, {categoryID:categoryID}, callbackHandler);
                
                
            }
            function callbackHandler(data)
            {
                
                jQuery("#ccc").html(data);
                
            }
        </script>
    </head>
    <body>
    
    
        <%
           DBUtil db=new DBUtil();
           DataTable  dt = db.QueryDataTable("Select CategoryID,CategoryName From Categories Order by CategoryID ASC");
           if(dt.Rows.size()>0)
           {
             out.print("<select name='categories' onchange='getProducts(this.value)'>");
             out.print("<option value='-1'>請選擇</option>");
             for(DataRow dr:dt.Rows)
             {
              out.print("<option value='"+dr.getValue("CategoryID") +"'>"+dr.getValue("CategoryName") +"</option>");
             }
             out.print("</select>");
           }
                                           
        %>
        <br/>
        <div id="ccc"></div>
    </body>
</html>

 

被Post的對象JSP

request.setCharacterEncoding("UTF-8");不需要這行Code

<%@page import="System.Data.DataRow"%>
<%@page import="System.Data.DataTable"%>
<%@page import="DAL.DBUtil"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%//上一行的pageEncoding必填,雖然單獨執行此JSP沒問題,若沒填pageEncoding的話,jQuery Ajax post會失敗%>
<%
String categoryID = request.getParameter("categoryID")!=null ? (String)request.getParameter("categoryID"):"-1";
//ASP.net的話,則是用Request["categoryID"]或Request.Form["categoryID"]來抓表單變數,Request.QueryString["categoryID"]會抓不到

if(!categoryID.equals("-1"))
{
    
 DBUtil db=new DBUtil();
 DataTable dt = db.QueryDataTable("Select p.ProductID,p.ProductName from Categories c" + 
                                  " Inner Join Products p " +
                                  " on c.CategoryID=p.CategoryID " +
                                  " Where c.CategoryID = '"+categoryID+"'");
 
 out.print("<select name='products'>");
 for(DataRow dr:dt.Rows)
 {
  out.print("<option value='"+dr.getValue("ProductID") +"'>"+dr.getValue("ProductName") +"</option>");
 }
 out.print("</select>");
}else
{
 out.print("");
}


%>

執行結果: