这里将介绍三种ajax的方式做省市二级菜单,基础知识在前一篇。直接看源码
1.以xml形式返回二级菜单栏(与数据库无关)
<body>
<select id="provinceID">
<option>选择省份</option>
<option>吉林省</option>
<option>辽宁省</option>
<option>山东省</option>
<option>湖南省</option>
</select>
<select id="cityID">
<option>选择城市</option>
</select>
<hr/>
<div>
<!-- 显示结果 -->
</div>
<script type="text/javascript">
document.getElementById("provinceID").onchange=function(){
//清空原来的city列表
var citySelectElement = document.getElementById("cityID");
var cityElementArray = citySelectElement.options;
var size = cityElementArray.length;
if(size > 1){
for(var i = size-1 ; i>0 ;i--){
citySelectElement.removeChild(cityElementArray[i])
}
}
var province = this[this.selectedIndex].innerHTML;
province = encodeURI(province);
//创建AJAX引警对象
var xhr = createXHR();
//设置函数监听
xhr.onreadystatechange = function(){
if(xhr.readyState==4){
if(xhr.status==200){
//以字符串形式接收
//var msg = xhr.responseText;
//以XML形式接收
var xmlDocument = xhr.responseXML;
var cityElementArray = xmlDocument.getElementsByTagName("city");
var size = cityElementArray.length;
for(var i = 0 ; i <size ; i++){
var city = cityElementArray[i].firstChild.nodeValue;
var optionElement = document.createElement("option");
optionElement.innerHTML = city;
document.getElementById("cityID").appendChild(optionElement);
}
}
}
}
//准备以get方式发送请求
xhr.open("get","/ajax/CityServlet?time="+new Date().getTime()+"&province="+province);
//真正发送请求
xhr.send(null);
}
function createXHR(){
var xhr = null;
try{
xhr = new ActiveXObject("microsoft.xmlhttp");
}catch(e){
try{
xhr = new XMLHttpRequest();
}catch(e){
window.alert("你的浏览器太差");
}
}
return xhr;
}
</script>
</body>
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("PostServlet::doGet()");
String province = request.getParameter("province");
byte[] buf = province.getBytes("ISO8859-1");
province = new String(buf,"UTF-8");
System.out.println("省份是:" + province);
String msg = null;
response.setContentType("text/xml;charset=UTF-8");
PrintWriter pw = response.getWriter();
//这里写的是返回的xml格式的文本
pw.write("<root>");
if(province.equals("吉林省")){
pw.write("<city>长春[吉林省]</city>");
pw.write("<city>吉林市[吉林省]</city>");
pw.write("<city>松原[吉林省]</city>");
pw.write("<city>通化[吉林省]</city>");
}else if(province.equals("辽宁省")){
pw.write("<city>沈阳[辽宁省]</city>");
pw.write("<city>大连[辽宁省]</city>");
pw.write("<city>鞍山[辽宁省]</city>");
pw.write("<city>抚顺[辽宁省]</city>");
pw.write("<city>铁岭[辽宁省]</city>");
}else if(province.equals("山东省")){
pw.write("<city>济南[山东省]</city>");
pw.write("<city>青岛[山东省]</city>");
pw.write("<city>威海[山东省]</city>");
}else{
pw.write("<city>xxx[xxx]</city>");
pw.write("<city>xxx[xxx]</city>");
pw.write("<city>xxx[xxx]</city>");
}
pw.write("</root>");
}
}
2 .以json形式返回二级菜单栏(与数据库无关)
这里有点尴尬的是:有人不会写json代码,不知道json数据的格式怎么写。晚点会有一篇介绍json的文章大家可以看一下。从下面我写json的代码来看,很容易出错,如果说写错了json格式的数据,后面接收数据可能会出现问题。因此推荐使用第三方工具解析 JSON。下面方法介绍咯
<body>
<select id="provinceID">
<option>选择省份</option>
<option>吉林省</option>
<option>辽宁省</option>
<option>山东省</option>
<option>湖南省</option>
</select>
<select id="cityID">
<option>选择城市</option>
</select>
<hr/>
<div>
<!-- 显示结果 -->
</div>
<script type="text/javascript">
document.getElementById("provinceID").onchange=function(){
//清空原来的city列表
var citySelectElement = document.getElementById("cityID");
var cityElementArray = citySelectElement.options;
var size = cityElementArray.length;
if(size > 1){
for(var i = size-1 ; i>0 ;i--){
citySelectElement.removeChild(cityElementArray[i])
}
}
var province = this[this.selectedIndex].innerHTML;
province = encodeURI(province);
//创建AJAX引警对象
var xhr = createXHR();
//设置函数监听
xhr.onreadystatechange = function(){
if(xhr.readyState==4){
if(xhr.status==200){
//以字符串形式接收
var jsonString = xhr.responseText;
//将json字符串转化成json格式
var jsonObject = eval("("+jsonString+")");
var size = jsonObject.length;
for(var i = 0 ; i < size ; i++){
var city = jsonObject[i].city_name;
var optionElement = document.createElement("option");
optionElement.innerHTML = city;
var divElemenet = document.getElementById("cityID");
divElemenet.appendChild(optionElement);
}
}
}
}
//准备以POST方式发送请求
xhr.open("get","/ajax/CityServlet1?time="+new Date().getTime()+"&province="+province);
//真正发送请求
xhr.send(null);
}
function createXHR(){
var xhr = null;
try{
xhr = new ActiveXObject("microsoft.xmlhttp");
}catch(e){
try{
xhr = new XMLHttpRequest();
}catch(e){
window.alert("你的浏览器太差");
}
}
return xhr;
}
</script>
</body>
CityServlet1
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String province = request.getParameter("province");
byte[] buf = province.getBytes("ISO8859-1");
province = new String(buf,"UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter pw = response.getWriter();
String jsonString = null;
if(province.equals("吉林省")){
jsonString="{'city':['长春','吉林市','松原','通化']}";
}else if(province.equals("辽宁省")){
jsonString="{'city':['沈阳','大连','鞍山','抚顺','铁岭']}";
}else if(province.equals("山东省")){
jsonString="{'city':['济南','青岛','威海']}";
}else{
jsonString = "{'city':['xxx1','xxx2','xxx3']}";
}
pw.write(jsonString);
}
3.第三方工具解析 JSON:把一个javaBean对象创建成json对象
开发步骤:看下面两张图片
第一步:导包,百度一下json包,全部导入就可以
第二部:了解两个类方法
JSONArray.fromObject(javaBean对象)
//设置javaBean转化成json时,不包含某个字段
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setExcludes(new String[]{“id”});
JSONArray jsonArray = JSONArray.fromObject(provinceList,jsonConfig);
![]()
ajax代码:
//注意这里的ajax.jsp代码不变。
//改变的是servlet传递数据的方式
CityServlet1
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String province = request.getParameter("province");
byte[] buf = province.getBytes("ISO8859-1");
province = new String(buf,"UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter pw = response.getWriter();
String jsonString = null;
List<City> cityList = new ArrayList<City>();
if(province.equals("吉林省")){
cityList.add(new City(1,"长春"));
cityList.add(new City(2,"吉林市"));
cityList.add(new City(3,"松原"));
cityList.add(new City(4,"通化"));
}else if(province.equals("辽宁省")){
cityList.add(new City(1,"沈阳"));
cityList.add(new City(2,"大连"));
cityList.add(new City(3,"鞍山"));
cityList.add(new City(4,"抚顺"));
cityList.add(new City(5,"铁岭"));
}else if(province.equals("山东省")){
cityList.add(new City(1,"济南"));
cityList.add(new City(2,"青岛"));
cityList.add(new City(3,"威海"));
}else{
cityList.add(new City(1,"xx"));
cityList.add(new City(2,"xx"));
cityList.add(new City(3,"xxx"));
}
//设置去掉javaBean中的id.这个id多余就不要生成Json了
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setExcludes(new String[]{"id"});
JSONArray jsonArray = JSONArray.fromObject(cityList, jsonConfig);
//注意哦,返回的值是字符串,所以应该把数组输出。不能直接返回JsonArray
jsonString = jsonArray.toString();
System.out.println(jsonArray.toString());
pw.write(jsonString);
}