需求:选择确定的省份以后,这个省的对应城市会自动提示到城市下拉框中 引用的是Json的处理方法
初始页面:
数据库中的数据:
初始页面的代码:
<%@ 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">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="js/city_json.js"></script>
</head>
<body>
省份: <select name="province" id ="province">
<option value="" >-请选择 -
<option value="1" >安徽
<option value="2" >江苏
<option value="3" >浙江
</select>
城市:
<select name="city" id="city">
<option value="" >-请选择 -
</select>
</body>
</html>
先建立Dao层接口:
package com.lishan.dao;
import java.sql.SQLException;
import java.util.List;
import com.lishan.util.CityBean;
public interface CityDao {
/**
* 根据省的pid找到省下面对应的城市名字
* @param pid
* @return
* @throws SQLException
*/
List<CityBean> findCity(Integer pid)throws SQLException;
}
再建立Dao层实现:
package com.lishan.dao.impl;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.lishan.dao.CityDao;
import com.lishan.util.CityBean;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class CityDaoImpl implements CityDao {
public List<CityBean> findCity(Integer pid) throws SQLException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
QueryRunner queryRunner = new QueryRunner(dataSource);
String sql ="select * from A wnere pid = ?";
queryRunner.query(sql, new BeanListHandler<CityBean>(CityBean.class),pid);
return null;
}
}
这里逻辑简单,就不再用service层,,直接到servlet
引用的是Json的处理方法
json依赖的jar包:
Servlet层代码:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//1. 获取参数
int pid = Integer.parseInt(request.getParameter("pid"));
//2 找出所有的城市
CityDao dao = new CityDaoImpl();
List<CityBean> list = dao.findCity(pid);
//3. 把list ---> json数据
//JSONArray ---> 变成数组 , 集合 []
//JSONObject ---> 变成简单的数据 { name : zhangsan , age:18}
JSONArray jsonArray = JSONArray.fromObject(list);
String json = jsonArray.toString();
System.out.println(json);
response.setContentType("text/html;charset=utf-8");
response.getWriter().write(json);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
};
}
JS相关代码:
$(function() {
//1。找到省份的元素
$("#province").change(function() {
//2. 一旦里面的值发生了改变,那么就去请求该省份的城市数据
//$("#province").varl();
var pid = $(this).val();
/*[
{
"cname": "深圳",
"id": 1,
"pid": 1
},
{
"cname": "东莞",
"id": 2,
"pid": 1
}
...
]*/
$.post( "CityServlet02",{pid:pid} ,function(data,status){
//先清空
$("#city").html("<option value='' >-请选择-");
//再遍历,追加
$(data).each(function(index , c) {
alert(index);
$("#city").append("<option value='"+c.id+"' >"+c.cname)
});
},"json" );
});
});
最终效果页面: