public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //text/html, text/xml, text/text response.setContentType("text/html;charset=utf-8"); Dao dao = new Dao(); List<Provincename> province = dao.findAllProvince(); String json = JSONArray.fromObject(province).toString(); response.getWriter().print(json); }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); int pid = Integer.parseInt(request.getParameter("pid")); System.out.println("pid="+pid); Dao dao = new Dao(); List<Cityname> cityList = dao.findByProvince(pid); String json = JSONArray.fromObject(cityList).toString(); System.out.println(json); response.getWriter().print(json); }
<script type="text/javascript"> function createXMLHttpRequest() { try { return new XMLHttpRequest();//大多数浏览器 } catch (e) { try { return ActvieXObject("Msxml2.XMLHTTP");//IE6.0 } catch (e) { try { return ActvieXObject("Microsoft.XMLHTTP");//IE5.5及更早版本 } catch (e) { alert("哥们儿,您用的是什么浏览器啊?"); throw e; } } } } window.onload = function() { var xmlHttp = createXMLHttpRequest(); xmlHttp.open("GET", "<c:url value ='/ProvinceServlet'/>", true); xmlHttp.send(null); xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { var proArray = eval("("+ xmlHttp.responseText+")") ; for(var i = 1;i<proArray.length;i++){ var pro = proArray[i];//pro是每一个省 var optionEle = document.createElement("option"); optionEle.value = pro.pid; var textNode = document.createTextNode(pro.name); optionEle.appendChild(textNode); document.getElementById("p").appendChild(optionEle); } } }; var proSelect = document.getElementById("p"); proSelect.onchange = function() { var xmlHttp = createXMLHttpRequest(); xmlHttp.open("POST", "<c:url value = '/CityServlet'/>", true); xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xmlHttp.send("pid=" + this.value); xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { var citySelect = document.getElementById("c"); var optionEleList = citySelect.getElementsByTagName("option"); while (optionEleList.length > 1) { citySelect.removeChild(optionEleList[1]); } var cityArray = eval("("+xmlHttp.responseText+")"); for(var i = 0;i<cityArray.length;i++){ var city = cityArray[i]; var optionEle = document.createElement("option"); optionEle.value = city.cid; var textNode = document.createTextNode(city.name); optionEle.appendChild(textNode); citySelect.appendChild(optionEle); } } }; }; }; </script> </head> <body> <h1>省市联动</h1> <select name="province" id="p"> <option>===请选择省===</option> </select> <select name="city" id="c"> <option>===请选择市===</option> </select> </body>