Ajax局部刷新实现三级联动
要实现从数据库获取出数据来实现联动,可以使用ajax(Asynchronous javascript and xml (异步的javascript 和 xml))局部刷新技术。ajax不是新的编程语言,而是一种局部刷新的技术,是局部刷新技术块的标准。
优点:不需要加载整个界面,就可以与服务器交互并且更新部分数据。ajax不需要任何浏览器插件,但是需要用户允许使用javascript在浏览器上运行。
实现省份、城市、地区三级联动
1、首先在数据库创建一张MyCity的数据表并添加数据,如图所示:
2、创建MyCity实体,并创建其get()set()方法
public class MyCity implements Serializable{ private static final long serialVersionUID = 1L; private int id ; //编号 private String name;//名称 private int status; //状态 private void MyCity() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } }
3、在dao层连接数据库,并创建获取省份的方法
public class CityDao { private Connection conn = null ; private PreparedStatement ps = null; private ResultSet rs = null; /** * 获取省份 * @param id * @return */ public ListgetPro(int id) { List citys = new ArrayList (); String sql = "select * from mycity where 1=1 "; if(id != 0){ sql += " and status = " + id ; }else{ sql += "and status is null "; } conn = DBUtil.getConn(); try { ps = conn.prepareStatement(sql); rs = ps.executeQuery(); while(rs.next()){ MyCity mycity = new MyCity(); mycity.setId(rs.getInt("id")); mycity.setName(rs.getString("name")); citys.add(mycity); } } catch (SQLException e) { e.printStackTrace(); }finally{ DBUtil.close(rs, ps, conn); } return citys; } }
4、创建CityServlet
public class CityServlet extends HttpServlet { private static final long serialVersionUID = 1L; private CityDao dao = new CityDao(); public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); //设置为xml类型 response.setContentType("text/xml;charset=utf-8"); PrintWriter out = response.getWriter(); //如果获取的id为空,则将新定义的id赋值为0,如果不为0则将获取到的id的值赋值给定义的id int id = null == request.getParameter("id")?0:Integer.parseInt(request.getParameter("id")); Listpros = dao.getPro(id); String msg = " "; } msg += ""; out.print(msg); out.flush(); out.close(); } }"; for (int i = 0; i "; msg += " "+mycity.getId()+" "; msg += ""+mycity.getName()+" "; msg += "
5、编写主页面(包括获取省份、城市、地区函数和创建XNLHttpRequest()引擎对象的函数及回调函数)
<%@ page language="java" pageEncoding="utf-8"%>ajax 三级联动 省份: 城市: 地区:
6、连接服务器,在浏览器显示的结果如下:
单击省份下拉列表框出现在数据库中添加的省份
[img]
[/img]
选择省份后,单击城市下拉列表框出现城市选项
[img]
[/img]
选择城市后,单击地区下拉列表框出现地区选项
[img]
[/img]
选择数据库中没有存放城市和地区的省份,则城市和地区下拉列表框中无选项
[img]
[/img]
[img]
[/img]