Ajax省市联动(下)
本帖最后由 webker 于 2015-12-8 18:43 编辑接下来,我们进入主题。
目前我们的思路是,服务端(即请求一个地址,这里是servlet),读取xml数据,生成省的数组,并通过ajax异步请求生成省的下拉选项页面,当选择某个省时触发onchange事件,将获取到的省作为请求参数传递给另一个页面,以生成市。当然这里会有一个小问题,待会我们再说。
html搞起
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form method="post">
<select name="province" id="pro">
<option>请选择省份</option>
</select>
<select name="city" id="c1">
<option>请选择市</option>
</select>
<input type="submit"/>
</form>
</body></html>
导入jar包,dom4j....
以下是部分省市xml数据:
<?xml version="1.0" encoding="utf-8"?>
<china>
<province name="北京">
<city>东城区</city>
<city>西城区</city>
<city>崇文区</city>
<city>宣武区</city>
<city>朝阳区</city>
<city>丰台区</city>
<city>石景山区</city>
<city>海淀区</city>
<city>门头沟区</city>
<city>房山区</city>
<city>通州区</city>
<city>顺义区</city>
<city>昌平区</city>
<city>大兴区</city>
<city>怀柔区</city>
<city>平谷区</city>
<city>密云县</city>
<city>延庆县</city>
</province>
<province name="天津">
<city>和平区</city>
<city>河东区</city>
<city>河西区</city>
<city>南开区</city>
<city>河北区</city>
<city>红桥区</city>
<city>塘沽区</city>
<city>汉沽区</city>
<city>大港区</city>
<city>东丽区</city>
<city>西青区</city>
<city>津南区</city>
<city>北辰区</city>
<city>武清区</city>
<city>宝坻区</city>
<city>宁河县</city>
<city>静海县</city>
<city>蓟县</city>
</province>
<province name="河北">
<city>石家庄</city>
<city>唐山</city>
<city>秦皇岛</city>
<city>邯郸</city>
<city>邢台</city>
<city>保定</city>
<city>张家口</city>
<city>承德</city>
<city>沧州</city>
<city>廊坊</city>
<city>衡水</city>
</province></china>
新建servlet,
Province.java
package test;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
public class Province extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
SAXReader reader=new SAXReader();
try {
Document doc=reader.read(this.getClass().getResourceAsStream("/china.xml"));//在src目录下找china.xml
List<Attribute> arrList=doc.selectNodes("//province/@name");//XPath表达式,选取所有province子元素名为name的所有属性,而不管它们在文档中的位置。
StringBuilder sb=new StringBuilder();
for(int i=0;i<arrList.size();i++){
sb.append(arrList.get(i).getValue());
if(i<arrList.size()-1){
sb.append(","); //最后一个不带,
}
}
response.getWriter().print(sb);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
修改html代码:
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form method="post">
<select name="province" id="pro">
<option>请选择省份</option>
</select>
<select name="city" id="c1">
<option>请选择市</option>
</select>
<input type="submit"/>
</form>
</body>
<script type="text/javascript">
var xml=new XMLHttpRequest();
xml.open("get","Province",true);
xml.send(null);
xml.onreadystatechange=function(){
if(xml.readyState==4 && xml.status==200){
var arr=xml.responseText; //获得返回数据,形如:北京,天津
var proarr=arr.split(",");//将字符串转为数组
for(var i=0;i<proarr.length;i++){//遍历数组
var tag=document.createElement("option");//创建option元素节点
var text=document.createTextNode(proarr); //创建文档节点
tag.value=proarr; //为option的value属性赋值
tag.appendChild(text);//将文本节点添加到option元素中
document.getElementById("pro").appendChild(tag); //在省的下拉列表添加选项option
}
}
};
</script>
</html>
看下效果。
然后,通过js,为省的选项添加onchange事件,
var pro=document.getElementById("pro");
pro.onchange=function(){
//这里获取市
}
新建servlet,City
City.java
package test;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class City extends HttpServlet {
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/xml;charset=utf-8");//设置响应类型为text/xml
request.setCharacterEncoding("utf-8");
SAXReader reader=new SAXReader();
try {
Document doc=reader.read(this.getClass().getResourceAsStream("/china.xml"));
String pname=request.getParameter("pname");//获取请求参数,省名
Element e=(Element) doc.selectSingleNode("//province[@name='"+pname+"']");//根据省名来获取单一节点
response.getWriter().print(e.asXML());//向浏览器返回xml数据。
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
最终html代码。。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form method="post">
<select name="province" id="pro">
<option>请选择省份</option>
</select>
<select name="city" id="c1">
<option>请选择市</option>
</select>
<input type="submit"/>
</form>
<%request.setCharacterEncoding("utf-8"); %>
<%=request.getParameter("province")%>
<%=request.getParameter("city")%>
</body>
<script type="text/javascript">
var xml=new XMLHttpRequest();
xml.open("get","Province",true);
xml.send(null);
xml.onreadystatechange=function(){
if(xml.readyState==4 && xml.status==200){
var arr=xml.responseText;
var proarr=arr.split(",");
for(var i=0;i<proarr.length;i++){
var tag=document.createElement("option");
var text=document.createTextNode(proarr);
tag.value=proarr;
tag.appendChild(text);
document.getElementById("pro").appendChild(tag);
}
}
};
var pro=document.getElementById("pro");
pro.onchange=function(){//当选择了省后执行函数体
xml.open("post","City",true);
xml.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xml.send("pname="+pro.value);//获取当前选择的省名
xml.onreadystatechange=function(){
if(xml.readyState==4 && xml.status==200){
var doc=xml.responseXML; //xml数据
var cityArr=doc.getElementsByTagName("city");//通过得到所有city元素
var parent=document.getElementById("c1");
var optionlist=parent.getElementsByTagName("option");
while(optionlist.length>1){
parent.removeChild(optionlist);//当添加市的选项时,删除原先的市选项
}
for(var i=0;i<cityArr.length;i++){
var cityEle=cityArr;
var cityName;
if(window.addEventListener){
cityName=cityEle.textContent;
}else{
cityName=cityEle.text; //IE获取元素的文本节点内容
}
var tag=document.createElement("option");
var text=document.createTextNode(cityName);
tag.appendChild(text);
parent.appendChild(tag);
}
}
};
};
</script>
</html>
ok了。吃饭去的。。写的不好,还请见谅。(*^__^*) 嘻嘻
by:webker 支持,看起来不错呢! 学习学习技术,加油! 感谢楼主的分享~ 支持中国红客联盟(ihonker.org) 支持,看起来不错呢! 还是不错的哦,顶了 支持,看起来不错呢! 感谢楼主的分享~ 支持,看起来不错呢!