AJAX 三级联动例题

Posted w944372441

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AJAX 三级联动例题相关的知识,希望对你有一定的参考价值。

用ajax三级联动写一个关于省市区下拉列表的联动

数据库中的表:

id是这条数据的主键,dname是地区名称,parentid是父级id

页面效果:

先实例化一个district类

package com.hanqi.model;

public class District {
	private String id;
	private String dname;
	private String parentid;
	public District(String id, String dname, String parentid) {
		super();
		this.id = id;
		this.dname = dname;
		this.parentid = parentid;
	}
	public District() {
		super();
		// TODO Auto-generated constructor stub
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getDname() {
		return dname;
	}
	public void setDname(String dname) {
		this.dname = dname;
	}
	public String getParentid() {
		return parentid;
	}
	public void setParentid(String parentid) {
		this.parentid = parentid;
	}
}

 连接数据库:

package com.hanqi.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class DBHelper {
	private static final String USERNAME = "test0315";
	private static final String PASSWORD = "123456";
	private static final String URL = "jdbc:oracle:thin:@localhost:1521:xe";
	private static final String CLASSNAME = "oracle.jdbc.OracleDriver";
	static {
		try {
			Class.forName(CLASSNAME);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static Connection getConnection() {
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}

	public static void destroy(Connection conn,PreparedStatement ps,ResultSet rs) {
		if(rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			rs = null;
		}
		if(conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			conn = null;
		}
		if(ps != null) {
			try {
				ps.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			ps = null;
		}
	}
	public static void main(String[] args) {
		System.out.println(getConnection());
	}
}

 数据库访问对象:

package com.hanqi.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.security.auth.Destroyable;

import com.hanqi.model.District;
import com.hanqi.util.DBHelper;

public class Basedao {
	private Connection conn;
	private PreparedStatement ps;
	private ResultSet rs;

	private ResultSet initQuery(String sql, Object... objects) throws SQLException {
		conn = DBHelper.getConnection();
		ps = conn.prepareStatement(sql);
		setParam(ps, objects);
		return ps.executeQuery();
	}

	private void setParam(PreparedStatement ps, Object[] objects) throws SQLException {
		int i = 1;
		for (Object o : objects) {
			ps.setObject(i, o);
			i++;
		}
	}

	public List<District> selectdistrict(String parentid) throws SQLException {
		List<District> list = new ArrayList<>();
		String sql = "select * from c_district where parentid = ?";
		rs = initQuery(sql, parentid);
		while (rs.next()) {
			District dt = new District();
			dt.setId(rs.getString("id"));
			dt.setDname(rs.getString("dname"));
			dt.setParentid(rs.getString("parentid"));
			list.add(dt);
		}
		DBHelper.destroy(conn, ps, rs);
		return list;
	}
}

 servlet类:

package com.hanqi.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.hanqi.dao.Basedao;
import com.hanqi.model.District;

/**
 * Servlet implementation class FindServlet
 */
@WebServlet("/FindServlet")
public class FindServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public FindServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String parentid = request.getParameter("parentid");
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset:utf-8");
		Basedao bd = new Basedao();
		JSONObject jo = new JSONObject();
		List<District> list = null;
		try {
			list = bd.selectdistrict(parentid);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		if (list != null && list.size() > 0) {
			jo.put("success", true);
			jo.put("result", list);
		} else {
			jo.put("seccess", false);
		}
		response.getWriter().write(jo.toJSONString());
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}

 JSP页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<title>Insert title here</title>
</head>
<body>
 省:<select id="province">
 	<option>===请选择===</option>
 </select>
 市:<select id="city">
 	<option>===请选择===</option>
 </select>
 区:<select id="area">
 	<option>===请选择===</option>
 </select>
</body>
</html>

 JS页面:

$(function() {//$() 此方法代表当JSP页面元素全部加载完成后再执行JS脚本
	$.ajax({//ajax方法调用,通过此方法接收前端信息发往后台并接受后台信息显示在前端
		type : "post",//发送请求的方式:post/get
		url : "FindServlet",//接收请求的地址
		dataType : "json",//接收后台数据的类型:text,html,json,xml
		data:{//这个ajax请求所携带的参数,是指前端的数据请求,以键值对方式存储,为可选项;
			parentid:"0"
		},
		success : function(data) {//当这个请求成功发送到后台时执行的方法,这里的data参数是指后台响应后发送来的字符串类型的数据;
			if (data.success) {//
				for (var i = 0; i < data.result.length; i++) {
					var district = data.result[i];//将数据里的对象遍历取出
					$("#province").append(//添加下拉选项
							"<option value=\'" + district.id + "\'>"//将id作为选项的值
									+ district.dname + "</option>");
				}
			}
		},
		error : function(msg) {//请求失败时执行的方法;

		}
	});
	$("#province").change(//当该选择器改变时执行该方法
			function() {//封装一个方法
				var provinceid = $(this).val();//获取该选项的值作为请求参数,this代表这个选择器;
				$.ajax({
					type : "post",
					url : "FindServlet",
					data : {
						parentid : provinceid
					},
					dataType : "json",
					success : function(data) {
						if (data.success) {
							$("#city").empty();//先将次级选项初始化,再添加下拉数据
							$("#city").append("<option>==请选择==</option>");
							$("#area").empty();
							$("#area").append("<option>===请选择===</option>");
							for (var i = 0; i < data.result.length; i++) {
								var district = data.result[i];
								$("#city").append(
										"<option value=\'" + district.id + "\'>"
												+ district.dname + "</option>");
							}
						} else {//如果查询不到数据也要对选项初始化,即清空
							$("#city").empty();
							$("#city").append("<option>==请选择==</option>");
							$("#area").empty();
							$("#area").append("<option>===请选择===</option>");
						}
					},
					error : function() {

					}
				});
			});
	
	$("#city").change(
		function(){
			var cityid = $(this).val();
			$.ajax({
				type :"post",
				url:"FindServlet",
				data:{
					parentid:cityid
				},
				dataType:"json",
				success:function(data){
					if(data.success){
						$("#area").empty();
						$("#area").append("<option>===请选择===</option>");
						for(var i = 0;i<data.result.length;i++){
							var district = data.result[i];
							$("#area").append
							("<option value=\'"+ district.id+"\' >"+district.dname+"</option>")
						}
						
					}else{
						$("#area").empty();
						$("#area").append("<option>===请选择===</option>");
					}
				},
				error:function(msg){
					alert("查询错误!");
				}
			});
		}
	);

});

 JS页面第二种写法:

$(function() {
	getData("0", "#province");//调用方法,将参数传进去
	$("#province").change(function() {
		var provinceid = $(this).val();
		getData(provinceid, "#city");
	});
	$("#city").change(function() {
		var cityid = $(this).val();
		getData(cityid, "#area");
	});

})
var getData = function(parentid, selector) {//将方法命名
	$.ajax({
		type : "post",
		url : "FindServlet",
		data : {
			parentid : parentid
		},
		dataType : "json",
		success : function(data) {
			if (data.success) {
				$(selector).empty();
				$(selector).append("<option>===请选择===</option>");
				$(selector + "select").empty();//获取该选择器后面紧挨的选择器,并清空
				$(selector + "select").append("<option>===请选择===</option>");
				for (var i = 0; i < data.result.length; i++) {
					var district = data.result[i];
					$(selector).append(
							"<option value=\'" + district.id + "\'>"
									+ district.dname + "</option>");
				};			
			}else{
				$(selector).empty();
				$(selector).append("<option>===请选择===</option>");
				$(selector + "select").empty();
				$(selector + "select").append("<option>===请选择===</option>");
			}		
			
		},
		error : function(msg) {
			alert("查询失败!")
		}
	});
}

 

以上是关于AJAX 三级联动例题的主要内容,如果未能解决你的问题,请参考以下文章

ajax省市区三级联动

三级联动日历例题

Ajax三级联动

PHP ajax 实现三级联动

三级联动 省市 ajax的代码

三级联动 省市 ajax的代码