极乐门资源网 Design By www.ioogu.com
实现Ajax实现省市区三级级联,需要Java解析json技术
整体Demo下载地址如下: 点我下载
address.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <script type="text/javascript"> /** * 得到XMLHttpRequest对象 */ function getajaxHttp() { var xmlHttp; try { // Firefox, Opera 8.0+, Safari xmlHttp = new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("您的浏览器不支持AJAX!"); return false; } } } return xmlHttp; } /** * 发送ajax请求 * url--请求到服务器的URL * methodtype(post/get) * con (true(异步)|false(同步)) * functionName(回调方法名,不需要引号,这里只有成功的时候才调用) * (注意:这方法有二个参数,一个就是xmlhttp,一个就是要处理的对象) */ function ajaxrequest(url, methodtype, con, functionName) { //获取XMLHTTPRequest对象 var xmlhttp = getajaxHttp(); //设置回调函数(响应的时候调用的函数) xmlhttp.onreadystatechange = function() { //这个函数中的代码在什么时候被XMLHTTPRequest对象调用? //当服务器响应时,XMLHTTPRequest对象会自动调用该回调方法 if (xmlhttp.readyState == 4) { if (xmlhttp.status == 200) { functionName(xmlhttp.responseText); } } }; //创建请求 xmlhttp.open(methodtype, url, con); //发送请求 xmlhttp.send(); } window.onload=function(){ ajaxrequest("addressSerlvet","POST",true,addrResponse); } //动态获取省的信息 function addrResponse(responseContents){ var jsonObj = new Function("return" + responseContents)(); for(var i = 0; i < jsonObj.addrList.length;i++){ document.getElementById('select').innerHTML += "<option value='"+jsonObj.addrList[i].id+"'>" +jsonObj.addrList[i].address+ "</option>" } } //选中省后 function pChange(){ //先将市的之前的信息清除 document.getElementById('selectCity').innerHTML="<option value='-1'>请选择市</option>"; //再将区的信息清除 document.getElementById('selectArea').innerHTML="<option value='-1'>请选择区</option>"; //再将用户的输入清楚 document.getElementById("addr").innerHTML=""; var val = document.getElementById('select').value; if(val == -1){ document.getElementById('selectCity')[0].selected = true; return; } //开始执行获取市 ajaxrequest("addressSerlvet"+val,"POST",true,cityResponse); } //获取市的动态数据 function cityResponse(responseContents){ var jsonObj = new Function("return" + responseContents)(); for(var i = 0; i < jsonObj.cityList.length;i++){ document.getElementById('selectCity').innerHTML += "<option value='"+jsonObj.cityList[i].id+"'>" +jsonObj.cityList[i].address+ "</option>" } } //选中市以后 function cChange(){ var val = document.getElementById('selectCity').value; //开始执行获取区 ajaxrequest("addressSerlvet"+val,"POST",true,areaResponse); } //获取区的动态数据 function areaResponse(responseContents){ var jsonObj = new Function("return" + responseContents)(); for(var i = 0; i < jsonObj.areaList.length;i++){ document.getElementById('selectArea').innerHTML += "<option value='"+jsonObj.areaList[i].id+"'>" +jsonObj.areaList[i].address+ "</option>" } } //点击提交按钮 function confirM(){ //获取省的文本值 var p = document.getElementById("select"); var pTex = p.options[p.options.selectedIndex].text; if(p.value=-1){ alert("请选择省"); return; } //获取市的文本值 var city = document.getElementById("selectCity"); var cityTex = city.options[city.options.selectedIndex].text; if(city.value=-1){ alert("请选择市"); return; } //获取区的文本值 var area = document.getElementById("selectArea"); var areaTex = area.options[area.options.selectedIndex].text; if(area.value=-1){ alert("请选择区"); return; } //获取具体位置id文本值 var addr = document.getElementById("addr").value; //打印 document.getElementById("show").innerHTML = "您选择的地址为 " + pTex + " " + cityTex + " " + areaTex + " " + addr; } </script> <body> <select id="select" onchange="pChange()"> <option value="-1">请选择省</option> </select> <select id="selectCity" onchange="cChange()"> <option value='-1'>请选择市</option> </select> <select id="selectArea" onchange="aChange()"> <option value='-1'>请选择市</option> </select> <input type="text" id="addr" /> <button onclick="confirM();">确定</button> <div id="show"></div> </body> </html>
AddressServlet.java
package cn.bestchance.servlet; import java.io.IOException; import java.util.ArrayList; 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 cn.bestchance.dao.AddressDao; import cn.bestchance.dao.impl.AddressDaoImpl; import cn.bestchance.entity.Address; import net.sf.json.JSONArray; import net.sf.json.JSONObject; @WebServlet("/addressSerlvet") public class AddressSerlvet extends HttpServlet { private static final long serialVersionUID = 1L; private AddressDao dao = new AddressDaoImpl(); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); String method=request.getParameter("method"); if("provincial".equals(method)){ getProvincial(request, response); } if("city".equals(method)){ getCity(request, response); } if("area".equals(method)){ getArea(request, response); } } /** * 根据市id获取该市下的区的全部信息 * @param request * @param response * @throws ServletException * @throws IOException */ protected void getArea(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String cityId = request.getParameter("cityId"); // 从数据库中查询省的信息 ArrayList<Address> areaList = dao.getAreaByCityId(Integer.parseInt(cityId)); // 将集合转成json字符串 JSONObject jsonObj = new JSONObject(); JSONArray jsonArray = JSONArray.fromObject(areaList); jsonObj.put("areaList", jsonArray); String jsonDataStr = jsonObj.toString(); response.getWriter().print(jsonDataStr); } /** * 获取省的信息 并相应 * @param request * @param response * @throws ServletException * @throws IOException */ protected void getProvincial(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 从数据库中查询省的信息 ArrayList<Address> addrList = dao.getProvince(); // 将集合转成json字符串 JSONObject jsonObj = new JSONObject(); JSONArray jsonArray = JSONArray.fromObject(addrList); jsonObj.put("addrList", jsonArray); String jsonDataStr = jsonObj.toString(); response.getWriter().print(jsonDataStr); } /** * 获取市的信息并相应 * @param request * @param response * @throws ServletException * @throws IOException */ protected void getCity(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String provinceId = request.getParameter("provincial"); // 从数据库中查询省的信息 ArrayList<Address> addrList = dao.getCityByProvinceId(Integer.parseInt(provinceId)); // 将集合转成json字符串 JSONObject jsonObj = new JSONObject(); JSONArray jsonArray = JSONArray.fromObject(addrList); jsonObj.put("cityList", jsonArray); String jsonDataStr = jsonObj.toString(); response.getWriter().print(jsonDataStr); } }
AddressDao.java
package cn.bestchance.dao; import java.util.ArrayList; import cn.bestchance.entity.Address; public interface AddressDao { /** * 获取省的id和名称 * @return */ ArrayList<Address> getProvince(); /** * 根据省的id获取市的信息 * @param provinceId * @return */ ArrayList<Address> getCityByProvinceId(int provinceId); /** * 根据市的id获取区的信息 * @param cityId * @return */ ArrayList<Address> getAreaByCityId(int cityId); }
AddressDaoImpl.java
package cn.bestchance.dao.impl; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import cn.bestchance.dao.AddressDao; import cn.bestchance.entity.Address; import cn.bestchance.util.DBUtil; public class AddressDaoImpl implements AddressDao { private DBUtil db = new DBUtil(); @Override public ArrayList<Address> getProvince() { ArrayList<Address> addrList = new ArrayList<Address>(); db.openConnection(); String sql = "select * from province"; ResultSet rs = db.excuteQuery(sql); try { while(rs.next()){ Address addr = new Address(); addr.setId(rs.getInt(2)); addr.setAddress(rs.getString(3)); addrList.add(addr); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(rs != null){ try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } db.closeResoure(); } return addrList; } @Override public ArrayList<Address> getCityByProvinceId(int provinceId) { ArrayList<Address> addrList = new ArrayList<Address>(); db.openConnection(); String sql = "select * from city where fatherID = " + provinceId; //431200 ResultSet rs = db.excuteQuery(sql); try { while(rs.next()){ Address addr = new Address(); addr.setId(rs.getInt(2)); addr.setAddress(rs.getString(3)); addrList.add(addr); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(rs != null){ try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } db.closeResoure(); } return addrList; } @Override public ArrayList<Address> getAreaByCityId(int cityId) { ArrayList<Address> addrList = new ArrayList<Address>(); db.openConnection(); String sql = "select * from area where fatherID = " + cityId; //431200 ResultSet rs = db.excuteQuery(sql); try { while(rs.next()){ Address addr = new Address(); addr.setId(rs.getInt(2)); addr.setAddress(rs.getString(3)); addrList.add(addr); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(rs != null){ try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } db.closeResoure(); } return addrList; } }
实体类Address.java
package cn.bestchance.entity; public class Address { @Override public String toString() { return "Address [id=" + id + ", address=" + address + "]"; } private int id; private String address; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Address() { super(); // TODO Auto-generated constructor stub } public Address(int id, String address) { super(); this.id = id; this.address = address; } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
极乐门资源网 Design By www.ioogu.com
极乐门资源网
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
极乐门资源网 Design By www.ioogu.com
暂无Ajax实现省市区三级级联(数据来自mysql数据库)的评论...
P70系列延期,华为新旗舰将在下月发布
3月20日消息,近期博主@数码闲聊站 透露,原定三月份发布的华为新旗舰P70系列延期发布,预计4月份上市。
而博主@定焦数码 爆料,华为的P70系列在定位上已经超过了Mate60,成为了重要的旗舰系列之一。它肩负着重返影像领域顶尖的使命。那么这次P70会带来哪些令人惊艳的创新呢?
根据目前爆料的消息来看,华为P70系列将推出三个版本,其中P70和P70 Pro采用了三角形的摄像头模组设计,而P70 Art则采用了与上一代P60 Art相似的不规则形状设计。这样的外观是否好看见仁见智,但辨识度绝对拉满。
更新日志
2024年12月26日
2024年12月26日
- 小骆驼-《草原狼2(蓝光CD)》[原抓WAV+CUE]
- 群星《欢迎来到我身边 电影原声专辑》[320K/MP3][105.02MB]
- 群星《欢迎来到我身边 电影原声专辑》[FLAC/分轨][480.9MB]
- 雷婷《梦里蓝天HQⅡ》 2023头版限量编号低速原抓[WAV+CUE][463M]
- 群星《2024好听新歌42》AI调整音效【WAV分轨】
- 王思雨-《思念陪着鸿雁飞》WAV
- 王思雨《喜马拉雅HQ》头版限量编号[WAV+CUE]
- 李健《无时无刻》[WAV+CUE][590M]
- 陈奕迅《酝酿》[WAV分轨][502M]
- 卓依婷《化蝶》2CD[WAV+CUE][1.1G]
- 群星《吉他王(黑胶CD)》[WAV+CUE]
- 齐秦《穿乐(穿越)》[WAV+CUE]
- 发烧珍品《数位CD音响测试-动向效果(九)》【WAV+CUE】
- 邝美云《邝美云精装歌集》[DSF][1.6G]
- 吕方《爱一回伤一回》[WAV+CUE][454M]