Ajax二级联动

需要的包
在这里插入图片描述

.jsp

<body>
省:
<select id="sheng" onchange="loadInfo()">
	<option value="1">江苏省</option>
	<option value="2">山东省</option>
	<option value="3">浙江省</option>
</select>
&nbsp;&nbsp;
市
<select id="shi">
</select>
</body>
<script type="text/javascript">
	function loadInfo(){
		var shengId=document.getElementById("sheng").value;
		var shi=document.getElementById("shi);
		shi.options.length=0;//每次需要将市的长度设置为0,不然每次改变会使option叠加
		var xmlHttp;
		if(window.XMLHttpRequest){
			xmlHttp=new XMLHttpRequest();
		}else{
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlHttp.onreadystatechange=function(){
			if(xmlHttp.readyState==4 && xmlHttp.status==200){
				alert(xmlHttp.responseText);
				var dataObj=eval("("+xmlHttp.responseText+")");
				for(var i=0;i<dataObj.rows.length;i++){
					var o=dataObj.rows[i];
					shi.options.add(new Option(o.text));//根据返回数据长度创建出新的option
				}
			}
		};
		xmlHttp.open("POST", "ej?shengId="+shengId, true);//post请求提交数据
		
	    xmlHttp.send();
	}
</script>

.java

@WebServlet("/ej")
public class TwoLevel extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html;charset=utf-8");//设置编码
		PrintWriter out=resp.getWriter();
		String shengId=req.getParameter("shengId");
		JSONObject resultJson=new JSONObject();
		JSONArray jsonArray=new JSONArray();
		JSONObject temp=null;
		switch(Integer.parseInt(shengId)){
			case 1:{
				temp=new JSONObject();temp.put("id", 1);temp.put("text", "南京");jsonArray.add(temp);
				temp=new JSONObject();temp.put("id", 2);temp.put("text", "南通");jsonArray.add(temp);
				temp=new JSONObject();temp.put("id", 3);temp.put("text", "泰兴");jsonArray.add(temp);
				break;
			}
			case 2:{
				temp=new JSONObject();temp.put("id", 4);temp.put("text", "济南");jsonArray.add(temp);
				temp=new JSONObject();temp.put("id", 5);temp.put("text", "烟台");jsonArray.add(temp);
				temp=new JSONObject();temp.put("id", 6);temp.put("text", "蓬莱");jsonArray.add(temp);
				break;
			}
			case 3:{
				temp=new JSONObject();temp.put("id", 7);temp.put("text", "杭州");jsonArray.add(temp);
				temp=new JSONObject();temp.put("id", 8);temp.put("text", "宁波");jsonArray.add(temp);
				temp=new JSONObject();temp.put("id", 9);temp.put("text", "温州");jsonArray.add(temp);
				break;
			}
		}
		resultJson.put("rows", jsonArray);
		out.println(resultJson);
		out.flush();
		out.close();
	}

}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值