生活随笔
收集整理的這篇文章主要介紹了
AJAX省市县三级联动的实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
省市縣數據
本例子中省市縣數據保存在MySQL數據庫中,部分數據截圖如下:
從數據庫中讀取數據
導入需要的jar包 連接池配置文件<c3p0-config><!-- 默認配置,如果沒有指定則使用這個配置 --><default-config><property name="driverClass">com.mysql.jdbc.Driver</property><property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/test</property><property name="user">root</property><property name="password">數據庫密碼</property><property name="checkoutTimeout">30000</property><property name="idleConnectionTestPeriod">30</property><property name="initialPoolSize">10</property><property name="maxIdleTime">30</property><property name="maxPoolSize">100</property><property name="minPoolSize">10</property><property name="maxStatements">200</property><user-overrides user="test-user"><property name="maxPoolSize">10</property><property name="minPoolSize">1</property><property name="maxStatements">0</property></user-overrides></default-config>
</c3p0-config>
JDBCUtils工具類文件
通用JDBCUtils工具類文件,使用時直接引入
package org.xueyao.ajax.utils;import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;import javax.sql.DataSource;import org.apache.tomcat.jni.Thread;import com.mchange.v2.c3p0.ComboPooledDataSource;public class JDBCUtils {private static ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();//使用ThreadLocal存取刪鏈接對象private static ThreadLocal<Connection> local = new ThreadLocal<>();public static Connection getConnection() throws SQLException{return comboPooledDataSource.getConnection();}public static DataSource getDataSource(){return comboPooledDataSource;}//從ThreadLocal獲取鏈接的方法public static Connection getCurrentConnection() throws SQLException{//先從ThreadLocal獲取中Connection connection = local.get();if(connection != null){System.out.println("從local獲取數據:"+connection);return connection;}else{//如果沒有,在從鏈接池獲取,存入ThreadLocal中Connection conn = comboPooledDataSource.getConnection();System.out.println("從連接池獲取數據:"+conn);local.set(conn);return conn;}}//開啟事務的方法public static void startTransaction() throws SQLException{Connection connection = getCurrentConnection();System.out.println(connection);connection.setAutoCommit(false);}//提交事務的方法public static void commit() throws SQLException{Connection connection = getCurrentConnection();System.out.println(connection);connection.commit();}//回滾事務的方法public static void rollback() throws SQLException{Connection connection = getCurrentConnection();System.out.println(connection);connection.rollback();}//釋放資源的方法public static void close() throws SQLException{Connection connection = getCurrentConnection();System.out.println(connection);local.remove();connection.close();}}
創建JavaBean文件package org.xueyao.ajax.domain;public class Province {private int codeid;private int parentid;private String cityName;public int getCodeid() {return codeid;}public void setCodeid(int codeid) {this.codeid = codeid;}public int getParentid() {return parentid;}public void setParentid(int parentid) {this.parentid = parentid;}public String getCityName() {return cityName;}public void setCityName(String cityName) {this.cityName = cityName;}@Overridepublic String toString() {return "Province [codeid=" + codeid + ", parentid=" + parentid+ ", cityName=" + cityName + "]";}}
創建Servlet文件,獲取省市縣數據package org.xueyao.ajax.linkage;import java.io.IOException;
import java.sql.SQLException;
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.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.xueyao.ajax.domain.Province;
import org.xueyao.ajax.utils.JDBCUtils;import flexjson.JSONSerializer;public class GetDataServlet extends HttpServlet {private static final long serialVersionUID = 1L;protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {int parentid = Integer.parseInt(request.getParameter("parentid"));String sql = "SELECT * FROM province WHERE parentid=?";QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());try {List<Province> list = qr.query(sql, new BeanListHandler<Province>(Province.class), parentid);//System.out.println(list);//將list集合轉換成json格式字符串JSONSerializer jsonSerializer = new JSONSerializer();String serialize = jsonSerializer.serialize(list);//System.out.println(serialize);//向頁面輸入字符串數據response.setContentType("text/html;charset=utf-8");response.getWriter().write(serialize);} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}}
從頁面顯示三級聯動
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="root" value="${pageContext.request.contextPath }"></c:set>
<!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">
<title>省市縣頁面</title>
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function() {//獲得三個下拉菜單元素var $pro = $("#province");var $city = $("#city");var $area = $("#area");$.get("${root}/getData?parentid=0",function(data) {//alert(data);//遍歷數據$(data).each(function(){//創建option標簽,并追加到省級菜單中$pro.append("<option value='"+this.codeid+"'>"+this.cityName+"</option>");}); },"json");//省級菜單選擇事件$pro.change(function(){//清空市縣菜單中數據,保留第一個屬性$city.prop("length",1);$area.prop("length",1);$.get("${root}/getData?parentid="+this.value,function(data) {$(data).each(function() {$city.append("<option value='"+this.codeid+"'>"+this.cityName+"</option>");});},"json");});//市級菜單選擇事件$city.change(function(){//清空縣菜單中數據,保留第一個屬性$area.prop("length",1);$.get("${root}/getData?parentid="+this.value,function(data) {$(data).each(function(){$area.append("<option value='"+this.codeid+"'>"+this.cityName+"</option>");});},"json"); });});
</script>
</head>
<body><center><select id="province" name="province"><option value="none">--請選擇省--</option></select><select id="city" name="city"><option value="none">--請選擇市--</option></select><select id="area" name="area"><option value="none">--請選擇縣--</option></select></center>
</body>
</html>
上面的javascript代碼可以優化成這樣:
function loadData(value, ele){$.get("${root}/getData?parentid="+value,function(data) {//遍歷數據$(data).each(function(){//創建option標簽,追加到菜單中ele.append("<option value='"+this.codeid+"'>"+this.cityName+"</option>");}); },"json");
}
$(function() {var $pro = $("#province");//加載省和直轄市數據loadData(0,$pro);//加載市$("#city,#area").change(function () {// 清空原來的數據$(this).nextAll().prop("length",1);loadData(this.value, $(this).next());});});
效果圖如下:
代碼托管于GitHub
轉載于:https://www.cnblogs.com/loveyous/p/7523060.html
總結
以上是生活随笔為你收集整理的AJAX省市县三级联动的实现的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。