JSP Ajax根据所选值填充下拉列表

JSP Ajax根据所选值填充下拉列表,第1张

JSP Ajax根据所选值填充下拉列表

我能够使用servlet来完成以下简单示例,以根据产品类别获取产品名称。您需要对其进行一些修改以适合您的特定方案。让我知道这是否有帮助并使您走上正确的道路…

HTML页面:

<html>    <head>        <script SRC="jquery.js" TYPE="text/javascript"></script>    </head>    <body>        <p> <label for="pcategory">Product Category</label> <select name="pcategory" id="pcategory" size="0">     <option value="1">Category 1</option>     <option value="2">Category 2</option>     <option value="3">Category 3</option> </select>        </p>        <p> <label for="pname">Product Name:</label> <select name="state" id="state">     <option value="1">Product Name 1 For Category 1</option>     <option value="2">Product Name 2 For Category 1</option>     <option value="3">Product Name 3 For Category 1</option> </select>        </p> </body>    <script type="text/javascript">        $category = $('#pcategory');        $category.change ( function() {     $.ajax({         type: "GET",         url: "GetProductName",         data: {category: $category.attr("selectedIndex") },         success: function(data){  $("#state").html(data)         }     }); }        );    </script></html>

servlet将为您提供产品名称…

import java.io.*;import javax.servlet.ServletException;import javax.servlet.http.*;public class GetProductName extends HttpServlet {    public void doGet(HttpServletRequest request, HttpServletResponse response)    throws ServletException, IOException {        response.setContentType("text/html;charset=UTF-8");        PrintWriter out = response.getWriter();        try { int category = Integer.parseInt(request.getParameter("category")); switch (category) {     case 1:out.print(  "<option value='1'>Product Name 1 For Category 2</option>" +  "<option value='2'>Product Name 2 For Category 2</option>" +  "<option value='3'>Product Name 3 For Category 2</option>"         );         break;     case 2:out.print(  "<option value='1'>Product Name 1 For Category 3</option>" +  "<option value='2'>Product Name 2 For Category 3</option>" +  "<option value='3'>Product Name 3 For Category 3</option>"         );         break;     default:         out.print(  "<option value='1'>Product Name 1 For Category 1</option>" +  "<option value='2'>Product Name 2 For Category 1</option>" +  "<option value='3'>Product Name 3 For Category 1</option>"         );         break; }        }  catch (Exception ex) { out.print("Error getting product name..." + ex.toString());        }        finally { out.close();        }    }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5651441.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存