html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>ajax json jquery 菜单案例</title> <style type="text/css"> *{margin:0;padding:0;} body { font-size: 13px; line-height: 130%; padding: 60px } </style> <link rel="stylesheet" type="text/css" href="../css/style.css"/> <script src="../js/jquery-2.1.1.min.js"></script> <script type="text/javascript"> $(function(){ $("#first").change(function() { var id=document.getElementById("first").value; $.ajax({ type: "POST", url: "../jsp/second1.jsp", data: "id="+id, dataType: "json", success: function(data) { var cityList=eval(data); var secondRoot=document.getElementById("second"); secondRoot.innerHTML=null; for(var i=0;i<data.length;i++) { var op = document.createElement("option"); op.innerHTML=cityList[i]; secondRoot.appendChild(op); } }, error:function(data){ alert(data); } }); }); }); </script> </head> <body> <select name="first" id="first" style="160px"> <option value="0">---请选择---</option> <option value="1" >中国</option> <option value="2">美国</option> <option value="3">英国</option> </select> <select name="second" id="second" size="3" style="160px"></select> </body> </html>
jsp
<%@ page contentType="text/html; charset=UTF-8" language="java"%> <%@ page import="java.util.*,net.sf.json.JSONArray" %> <% String idStr = (String)request.getParameter("id"); int id = idStr == null ? 1 : Integer.parseInt(idStr); switch(id){ case 1: out.println(JSONArray.fromObject("['上海','广州','山东']")); break; case 2: out.println(JSONArray.fromObject("['美国1','美国2','美国3']")); break; case 3: out.println(JSONArray.fromObject("['英国1','英国2','英国3']")); break; } %>