首页 > Java开发 > 一个简单的基于AJAX的二级联动实例

一个简单的基于AJAX的二级联动实例

效果:

1.选择省份后,自动加载省份对应的城市。
2.所有省份以及城市的信息保存在xml文件中。
原理:
当页面加载完毕后,XMLHttpRequest对象向一个servlet发出请求,请求省份及城市数据,获取数据后,将数据填充到对应的select标签中。提交表单后,表单也会请求另一个servlet处理该表单,获取城市与省份信息。

下面贴出代码:
1.jsp页面,为方便观看,js文件直接写入jsp页面:
[html]
  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
  2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  3. <html>
  4.     <head>
  5.         <title>My JSP 'responseXML.jsp' starting page</title>
  6.         <script type="text/javascript">
  7.     window.onload = function() {
  8.         var data = false;
  9.         var xhr = createXmlHttpRequest();
  10.         //请求服务端的一个servlet,该servlet可以读取xml文件,并将结果作为字符串返回。
  11.         xhr.open("get","${pageContext.request.contextPath}/servlet/ResponseXMLServlet?time="+new Date().getTime());
  12.         xhr.send(null);//由于是get请求所以发送数据为空
  13.         xhr.onreadystatechange = function()
  14.         {
  15.             if(xhr.readyState == 4)
  16.             {
  17.                 if(xhr.status == 200 || xhr.status == 304)
  18.                 {
  19.                     var xmlData = xhr.responseXML;//读取服务端返回的数据,是一个Object对象类型
  20.                     //获取xmlData对象中所有的省份并添加到对应select节点里
  21.                     var provinces = xmlData.getElementsByTagName("province");
  22.                     for(var i = 0; i < provinces.length; i++)
  23.                     {
  24.                         //alert(provinces[i].getAttribute("name"));//取出xml文件中每个province节点的name属性值
  25.                         var optionElement = document.createElement("option");//创建option节点
  26.                         optionElement.setAttribute("value",provinces[i].getAttribute("name"));//设置option节点的value属性值
  27.                         optionElement.innerText = provinces[i].getAttribute("name");//设置option标签的内部文本
  28.                         document.getElementById("province").appendChild(optionElement);//加到select节点下
  29.                     }
  30.                     data = xmlData;//将服务端返回的数据赋值给全局变量data
  31.                 }
  32.             }
  33.         }
  34.         document.getElementById("province").onchange = function()//为选择省份的select标签添加事件
  35.         {
  36.             //获取当前选择的省份
  37.             var province = document.getElementById("province").value;
  38.             //从xml数据中获取该省份下城市
  39.             var provinceElements = data.getElementsByTagName("province");
  40.             for(var i = 0; i < provinceElements.length; i++)
  41.             {
  42.                 if(provinceElements[i].getAttribute("name") == province)
  43.                 {
  44.                     var cityElements = provinceElements[i].getElementsByTagName("city");
  45.                     clearCitys();
  46.                     for(var j = 0; j < cityElements.length;j++)
  47.                     {
  48.                         var optionElement = document.createElement("option");//生成option节点
  49.                         optionElement.setAttribute("value",cityElements[j].firstChild.nodeValue);
  50.                         optionElement.innerText = cityElements[j].firstChild.nodeValue;
  51.                         document.getElementById("city").appendChild(optionElement);
  52.                     }
  53.                 }
  54.             }
  55.         }
  56.     }
  57.       function clearCitys(){ //清空城市信息
  58.         var city = document.getElementById('city');
  59.         city.options.length = 0;
  60.         city.options[0] = new Option('请选择城市...', 'null_city');
  61.     }
  62.     function createXmlHttpRequest() {//创建XMLHttpRequest对象
  63.         var xmlHttp;
  64.         try { //Firefox, Opera 8.0+, Safari
  65.             xmlHttp = new XMLHttpRequest();
  66.         } catch (e) {
  67.             try { //Internet Explorer
  68.                 xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
  69.             } catch (e) {
  70.                 try {
  71.                     xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  72.                 } catch (e) {
  73.                 }
  74.             }
  75.         }
  76.         return xmlHttp;
  77.     }
  78. </script>
  79.     </head>
  80.     <body>
  81.         <form action="${pageContext.request.contextPath }/servlet/HandFormServlet" method="post">
  82.             省份
  83.             <select name="province" id="province">
  84.                 <option value="null_province">
  85.                     请选择...
  86.                 </option>
  87.             </select>
  88.             城市
  89.             <select name="city" id="city">
  90.                 <option value="null_city">
  91.                     请选择...
  92.                 </option>
  93.             </select>
  94.             <br/>
  95.             <input type="submit" value="提交"/>
  96.         </form>
  97.     </body>
  98. </html>
获取xml文件信息并返回的servlet:
注:这里使用了dom4j读取一个xml文件(需要导入jar包),其实也可以用javaI/O,因为这个servlet只用读取文件并不用解析。
[java]
  1. package cn.edu.chd.web;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.io.PrintWriter;
  5. import javax.servlet.ServletException;
  6. import javax.servlet.http.HttpServlet;
  7. import javax.servlet.http.HttpServletRequest;
  8. import javax.servlet.http.HttpServletResponse;
  9. import org.dom4j.Document;
  10. import org.dom4j.DocumentException;
  11. import org.dom4j.io.SAXReader;
  12. public class ResponseXMLServlet extends HttpServlet
  13. {
  14.     @Override
  15.     protected void doGet(HttpServletRequest req, HttpServletResponse resp)
  16.             throws ServletException, IOException
  17.     {
  18.         resp.setCharacterEncoding("utf-8");
  19. //        告诉浏览器接收的是xml数据
  20.         resp.setContentType("application/xml;charset=utf-8");
  21.         PrintWriter writer = resp.getWriter();
  22. //        获取代表省份和城市信息的xml文件
  23.         String realPath = this.getServletContext().getRealPath("/data/data.xml");
  24.         SAXReader reader = null;
  25.         try
  26.         {
  27.             reader = new SAXReader();
  28.             Document doc = reader.read(new File(realPath));
  29.             writer.println(doc.asXML());//将文档对象作为字符串返回
  30.         } catch (DocumentException e)
  31.         {
  32.             e.printStackTrace();
  33.         }
  34.     }
  35.     @Override
  36.     protected void doPost(HttpServletRequest req, HttpServletResponse resp)
  37.             throws ServletException, IOException
  38.     {
  39.         this.doGet(req, resp);
  40.     }
  41. }

保存省份与城市的xml:

[html]
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <china>
  3.     <province name="吉林">
  4.         <city>长春</city>
  5.         <city>吉林市</city>
  6.         <city>通化</city>
  7.         <city>四平</city>
  8.     </province>
  9.     <province name="安徽">
  10.         <city>安庆</city>
  11.         <city>芜湖</city>
  12.         <city>合肥</city>
  13.         <city>六安</city>
  14.     </province>
  15.     <province name="江苏">
  16.         <city>南京</city>
  17.         <city>无锡</city>
  18.         <city>镇江</city>
  19.         <city>连云港</city>
  20.     </province>
  21.     <province name="山东">
  22.         <city>青岛</city>
  23.         <city>烟台</city>
  24.         <city>济南</city>
  25.         <city>威海</city>
  26.     </province>
  27. </china>
处理表单的servlet:
注:为了方便,直接打印到控制台。
[java]
  1. package cn.edu.chd.web;
  2. import java.io.IOException;
  3. import javax.servlet.ServletException;
  4. import javax.servlet.http.HttpServlet;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7. public class HandFormServlet extends HttpServlet
  8. {
  9.     @Override
  10.     protected void doGet(HttpServletRequest req, HttpServletResponse resp)
  11.             throws ServletException, IOException
  12.     {
  13.         req.setCharacterEncoding("utf-8");
  14.         resp.setCharacterEncoding("utf-8");
  15.         resp.setContentType("text/html;charset=utf-8");
  16.         String province = req.getParameter("province");
  17.         String city = req.getParameter("city");
  18.         System.out.println("province = "+province+",city = "+city);
  19.     }
  20.     @Override
  21.     protected void doPost(HttpServletRequest req, HttpServletResponse resp)
  22.             throws ServletException, IOException
  23.     {
  24.         this.doGet(req, resp);
  25.     }
  26. }

本文固定链接: http://www.devba.com/index.php/archives/4700.html | 开发吧

报歉!评论已关闭.