方法一:(纯javascript+jsp+servlet)
<script type="text/javascript">
var request = getRequest();
function getRequest(){
var request;
if(window.XMLHttpRequest){
request = new XMLHttpRequest();
//alert("xmlRequestHttp");
}
else{
request = new ActiveXObject("Microsoft.XMLHTTP");
alert("xobject");
}
return request;
}
function fun_init(){
// alert("init");
var url = '<%=request.getContextPath()%>/CityLinkServlet?level=1';
request.open('POST',url,true);
request.onreadystatechange = show_province;
request.send(null);
}
function change_province(_level,_code){
//alert(_level);
var url = '<%=request.getContextPath()%>/CityLinkServlet?level='+_level+'&code='+_code;
request.open('POST',url,true);
request.onreadystatechange = show_city;
request.send(null);
}
function change_city(_level,_code){
//alert(_level);
var url = '<%=request.getContextPath()%>/CityLinkServlet?level='+_level+'&code='+_code;
request.open('POST',url,true);
request.onreadystatechange = show_county;
request.send(null);
}
function show_province(){
if(request.readyState == 4){
if(request.status == 200){
var ret = request.responseText;
var jsonObj = eval("("+ret+")");
//alert(jsonObj.data.length);
//alert(document.getElementById("province"));
var obj = document.getElementById("province");
for(var i=0;i<jsonObj.length;i++){
var item = new Option(jsonObj[i].name,jsonObj[i].code);
obj.options.add(item);
}
}
}
}
function show_city(){
if(request.readyState == 4){
if(request.status == 200){
var ret = request.responseText;
var jsonObj = eval("("+ret+")");
var obj = document.getElementById("city");
obj.options.length = 1;
for(var i=0;i<jsonObj.length;i++){
var item = new Option(jsonObj[i].name,jsonObj[i].code);
obj.options.add(item);
}
}
}
}
function show_county(){
//alert(request);
if(request.readyState == 4){
if(request.status == 200){
var ret = request.responseText;
var jsonObj = eval("("+ret+")");
var obj = document.getElementById("county");
obj.options.length = 1;
for(var i=0;i<jsonObj.length;i++){
var item = new Option(jsonObj[i].name,jsonObj[i].code);
obj.options.add(item);
}
//alert(jsonObj.data.length);
}
}
}
</script>
</head>
<body onload="fun_init()">
<div>
<label>省</label>
<select id="province" onchange="change_province(2,this.value)">
<option value="--">---请选择---</option>
</select>
<br/>
<label>市</label>
<select id="city" onchange = "change_city(3,this.value)">
<option value="--">---请选择---</option>
</select>
<br/>
<label>县</label>
<select id="county">
<option value="--">---请选择---</option>
</select>
<br/>
</div>
</body>
</html>
方法二:(jquery+jsp+servlet)
<script type="text/javascript" src="<%=request.getContextPath()%>/jquery/jquery-1.7.1.js"></script>
<script type="text/javascript">
$(function(){
var $province = $("#province");
var $city = $("#city");
var $county = $("#county");
//省份选择框变化处理函数
$province.change(function(){
//alert($province.val());
$city[0].options.length = 1;
$county[0].options.length = 1;
$.ajax({
type:'post',
url:'<%=request.getContextPath()%>/CityLinkServlet',
dataType:'json',
data:{level:'2',code:$province.val()},
success:function(ret){
$.each(ret,function(){
$city.append("<option value="+this.code+">"+this.name+"</option>");
});
},
error:function(){alert("出现未知故障");}
});
});
//市选择框变化处理函数
$city.change(function(){
// alert($city.val());
$county[0].options.length = 1;
$.ajax({
type:'post',
url:'<%=request.getContextPath()%>/CityLinkServlet',
dataType:'json',
data:{level:'3',code:$city.val()},
success:function(ret){
$.each(ret,function(){
$county.append("<option value="+this.code+">"+this.name+"</option>");
});
},
error:function(){alert("出现未知故障");}
});
});
//页面加载完毕查询省份信息
$.ajax({
type:"post",
url:"<%=request.getContextPath()%>/CityLinkServlet",
data:{level:"1"},
dataType:"json",
success:function(ret){
$.each(ret,function(){
$province.append("<option value="+this.code+">"+this.name+"</option>");
});
},
error:function(){alert("出现未知故障");}
});
});
</script>
</head>
<body>
<div>
<label>省</label>
<select id="province">
<option value="--">---请选择---</option>
</select>
<br/>
<label>市</label>
<select id="city">
<option value="--">---请选择---</option>
</select>
<br/>
<label>县</label>
<select id="county">
<option value="--">---请选择---</option>
</select>
<br/>
</div>
</body>
</html>
方法三:(extjs4.0+jsp+servlet)
<%String conPath = request.getContextPath(); %>
<link href="<%=conPath %>/extjs4.0/resources/css/ext-all.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="<%=conPath%>/extjs4.0/ext-all.js"></script>
<script type="text/javascript" src="<%=conPath%>/extjs4.0/ext-lang-zh_CN.js"></script>
<script type="text/javascript">
Ext.require("Ext.*");
Ext.onReady(function(){
//定义combox模型
Ext.define('State',{
extend:'Ext.data.Model',
fields:[
{type:'string',name:'code'},
{type:'string',name:'name'}
]
});
//加载省数据源
var province_store = Ext.create('Ext.data.Store',{
model:'State',
proxy:{
type:'ajax',
url:'<%=request.getContextPath()%>/CityLinkServlet?level=1'
},
autoLoad:true,
remoteSort:true
});
//加载市数据源
var city_store = Ext.create('Ext.data.Store',{
model:'State',
proxy:{
type:'ajax',
url:'<%=request.getContextPath()%>/CityLinkServlet?level=2'
},
autoLoad:false,
remoteSort:true
});
//加载县数据源
var county_store = Ext.create('Ext.data.Store',{
model:'State',
proxy:{
type:'ajax',
url:'<%=request.getContextPath()%>/CityLinkServlet?level=3'
},
autoLoad:false,
remoteSort:true
});
//创建显示面板
Ext.create('Ext.panel.Panel',{
renderTo:document.body,
width:300,
height:220,
title:'省市县三级联动',
plain:true,
margin:'30 10 50 80',
bodyStyle:'padding:45px,15px,15px,15px',
defaults:{
autoScroll:true,
bodyPadding:10
},
items:[{
xtype:'combo',
name:'province',
id:'province',
fieldLabel:'选择省',
displayField:'name',
valueField:'code',
store:province_store,
triggerAction:'all',
queryMode:'local',
//selectOnFocus:true,
forceSelection:true,
allowBlank:false,
editable:false,
emptyText:'--请选择省--',
blankText:'--请选择省--',
listeners:{
select:function(combo,record,index){
//alert(this.value);
try{
var cityObj = Ext.getCmp('city');
cityObj.clearValue();
cityObj.store.load({params:{code:this.value}});
}catch(ex){
Ext.MessageBox.alert("错误","数据加载失败");
}
}
}
},
{
xtype:'combo',
name:'city',
id:'city',
fieldLabel:'选择市',
displayField:'name',
valueField:'code',
store:city_store,
triggerAction:'all',
queryMode:'local',
//selectOnFocus:true,
forceSelection:true,
allowBlank:false,
editable:false,
emptyText:'--请选择市--',
blankText:'--请选择市--',
listeners:{
select:function(combo,record,index){
try{
var countyObj = Ext.getCmp('county');
countyObj.clearValue();
countyObj.store.load({params:{code:this.value}});
}catch(ex){
Ext.MessageBox.alert("错误","数据加载失败");
}
}
}
},
{
xtype:'combo',
name:'county',
id:'county',
fieldLabel:'选择县',
displayField:'name',
valueField:'code',
store:county_store,
triggerAction:'all',
queryMode:'local',
//selectOnFocus:true,
forceSelection:true,
allowBlank:false,
editable:false,
emptyText:'--请选择县--',
blankText:'--请选择县--'
}]
});
});
</script>
</head>
<body>
</body>
</html>
后台代码:
package com.servlet;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.util.DBUtil;
/**
* Servlet implementation class CityLink
*/
public class CityLinkServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException
{
System.out.println("----in ---service");
String level = request.getParameter("level");
System.out.println("level=========="+level);
String code = request.getParameter("code");
System.out.println("code========"+code);
String sql = null;
if ("1".equals(level))
{
sql = "select dm,mc from city where dm like '%0000' order by dm";
deal(sql, response);
}
else if ("2".equals(level))
{
sql = "select dm,mc from city where dm like '" + code.substring(0, 2) + "%00' and dm != '" + code
+ "' order by dm";
deal(sql, response);
}
else if ("3".equals(level))
{
sql = "select dm,mc from city where dm like '" + code.substring(0, 4) + "%' and dm != '" + code
+ "' order by dm";
deal(sql, response);
}
else
{
}
}
public void deal(String sql, HttpServletResponse response)
{
Connection conn = DBUtil.getConnection();
ResultSet rs = null;
PreparedStatement pst = null;
try
{
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = null;
int i = 0;
while (rs.next())
{
jsonObject = new JSONObject();
jsonObject.put("code", rs.getString(1)).put("name", rs.getString(2));
jsonArray.put(i++, jsonObject);
}
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("data", jsonArray);
response.setCharacterEncoding("utf-8");
response.getWriter().println(jsonArray);
//response.getWriter().println(jsonObject2);
System.out.println(jsonArray.toString());
}
catch (SQLException e)
{
e.printStackTrace();
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
DBUtil.close(conn, pst, rs);
}
}
}
DButil。java
package com.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
public class DBUtil
{
private static String driverClassName ;
private static String username;
private static String password;
private static String url;
private static ResourceBundle bundle = ResourceBundle.getBundle("jdbc-mysql");
static{
driverClassName = bundle.getString("driverClassName").trim();
username = bundle.getString("username").trim();
password = bundle.getString("password").trim();
url = bundle.getString("url").trim();
try
{
Class.forName(driverClassName);
}
catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
System.out.println("找不到jdbc驱动包");
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 close(Connection conn){
if(conn!=null){
try
{
conn.close();
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
conn = null;
}
conn = null;
}
}
public static void close(Statement stmt){
if(stmt!=null){
try
{
stmt.close();
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
stmt = null;
}
stmt = null;
}
}
public static void close(PreparedStatement pst){
if(pst!=null){
try
{
pst.close();
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
pst = null;
}
pst = null;
}
}
public static void close(ResultSet rs){
if(rs!=null){
try
{
rs.close();
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
rs = null;
}
rs = null;
}
}
public static void close(Connection conn,java.sql.PreparedStatement stmt){
close(stmt);
close(conn);
}
public static void close(Connection conn,java.sql.PreparedStatement pst,ResultSet rs){
close(rs);
close(pst);
close(conn);
}
public static void close(Connection conn,Statement stmt){
close(stmt);
close(conn);
}
public static void close(Connection conn,Statement stmt,ResultSet rs){
close(rs);
close(stmt);
close(conn);
}
}
本文介绍了一种使用javascript、jquery和extjs实现的三级联动省市区县数据加载方式,包括请求处理、数据源加载及展示。同时提供了后台代码实现,通过SQL查询数据库获取数据并返回JSON格式。
3892

被折叠的 条评论
为什么被折叠?



