Ajax實(shí)現(xiàn)省市區(qū)三級(jí)級(jí)聯(lián)(數(shù)據(jù)來(lái)自mysql數(shù)據(jù)庫(kù))
實(shí)現(xiàn)Ajax實(shí)現(xiàn)省市區(qū)三級(jí)級(jí)聯(lián),需要Java解析json技術(shù)
整體Demo下載地址如下: 點(diǎn)我下載
address.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <script type="text/javascript"> /** * 得到XMLHttpRequest對(duì)象 */ 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; } /** * 發(fā)送ajax請(qǐng)求 * url--請(qǐng)求到服務(wù)器的URL * methodtype(post/get) * con (true(異步)|false(同步)) * functionName(回調(diào)方法名,不需要引號(hào),這里只有成功的時(shí)候才調(diào)用) * (注意:這方法有二個(gè)參數(shù),一個(gè)就是xmlhttp,一個(gè)就是要處理的對(duì)象) */ function ajaxrequest(url, methodtype, con, functionName) { //獲取XMLHTTPRequest對(duì)象 var xmlhttp = getajaxHttp(); //設(shè)置回調(diào)函數(shù)(響應(yīng)的時(shí)候調(diào)用的函數(shù)) xmlhttp.onreadystatechange = function() { //這個(gè)函數(shù)中的代碼在什么時(shí)候被XMLHTTPRequest對(duì)象調(diào)用? //當(dāng)服務(wù)器響應(yīng)時(shí),XMLHTTPRequest對(duì)象會(huì)自動(dòng)調(diào)用該回調(diào)方法 if (xmlhttp.readyState == 4) { if (xmlhttp.status == 200) { functionName(xmlhttp.responseText); } } }; //創(chuàng)建請(qǐng)求 xmlhttp.open(methodtype, url, con); //發(fā)送請(qǐng)求 xmlhttp.send(); } window.onload=function(){ ajaxrequest("addressSerlvet?method=provincial","POST",true,addrResponse); } //動(dòng)態(tài)獲取省的信息 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'>請(qǐng)選擇市</option>"; //再將區(qū)的信息清除 document.getElementById('selectArea').innerHTML="<option value='-1'>請(qǐng)選擇區(qū)</option>"; //再將用戶的輸入清楚 document.getElementById("addr").innerHTML=""; var val = document.getElementById('select').value; if(val == -1){ document.getElementById('selectCity')[0].selected = true; return; } //開(kāi)始執(zhí)行獲取市 ajaxrequest("addressSerlvet?method=city&provincial="+val,"POST",true,cityResponse); } //獲取市的動(dòng)態(tài)數(shù)據(jù) 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; //開(kāi)始執(zhí)行獲取區(qū) ajaxrequest("addressSerlvet?method=area&cityId="+val,"POST",true,areaResponse); } //獲取區(qū)的動(dòng)態(tài)數(shù)據(jù) 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>" } } //點(diǎn)擊提交按鈕 function confirM(){ //獲取省的文本值 var p = document.getElementById("select"); var pTex = p.options[p.options.selectedIndex].text; if(p.value=-1){ alert("請(qǐng)選擇省"); return; } //獲取市的文本值 var city = document.getElementById("selectCity"); var cityTex = city.options[city.options.selectedIndex].text; if(city.value=-1){ alert("請(qǐng)選擇市"); return; } //獲取區(qū)的文本值 var area = document.getElementById("selectArea"); var areaTex = area.options[area.options.selectedIndex].text; if(area.value=-1){ alert("請(qǐng)選擇區(qū)"); 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">請(qǐng)選擇省</option> </select> <select id="selectCity" onchange="cChange()"> <option value='-1'>請(qǐng)選擇市</option> </select> <select id="selectArea" onchange="aChange()"> <option value='-1'>請(qǐng)選擇市</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); } } /** * 根據(jù)市id獲取該市下的區(qū)的全部信息 * @param request * @param response * @throws ServletException * @throws IOException */ protected void getArea(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String cityId = request.getParameter("cityId"); // 從數(shù)據(jù)庫(kù)中查詢省的信息 ArrayList<Address> areaList = dao.getAreaByCityId(Integer.parseInt(cityId)); // 將集合轉(zhuǎn)成json字符串 JSONObject jsonObj = new JSONObject(); JSONArray jsonArray = JSONArray.fromObject(areaList); jsonObj.put("areaList", jsonArray); String jsonDataStr = jsonObj.toString(); response.getWriter().print(jsonDataStr); } /** * 獲取省的信息 并相應(yīng) * @param request * @param response * @throws ServletException * @throws IOException */ protected void getProvincial(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 從數(shù)據(jù)庫(kù)中查詢省的信息 ArrayList<Address> addrList = dao.getProvince(); // 將集合轉(zhuǎn)成json字符串 JSONObject jsonObj = new JSONObject(); JSONArray jsonArray = JSONArray.fromObject(addrList); jsonObj.put("addrList", jsonArray); String jsonDataStr = jsonObj.toString(); response.getWriter().print(jsonDataStr); } /** * 獲取市的信息并相應(yīng) * @param request * @param response * @throws ServletException * @throws IOException */ protected void getCity(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String provinceId = request.getParameter("provincial"); // 從數(shù)據(jù)庫(kù)中查詢省的信息 ArrayList<Address> addrList = dao.getCityByProvinceId(Integer.parseInt(provinceId)); // 將集合轉(zhuǎn)成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(); /** * 根據(jù)省的id獲取市的信息 * @param provinceId * @return */ ArrayList<Address> getCityByProvinceId(int provinceId); /** * 根據(jù)市的id獲取區(qū)的信息 * @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; } }
實(shí)體類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; } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- PHP+Mysql+Ajax+JS實(shí)現(xiàn)省市區(qū)三級(jí)聯(lián)動(dòng)
- java AJAX實(shí)現(xiàn)級(jí)聯(lián)下拉框
- ThinkPHP使用心得分享-ThinkPHP + Ajax 實(shí)現(xiàn)2級(jí)聯(lián)動(dòng)下拉菜單
- Ajax二級(jí)聯(lián)動(dòng)菜單實(shí)現(xiàn)原理及代碼
- ASP.NET Ajax級(jí)聯(lián)DropDownList實(shí)現(xiàn)代碼
- 一個(gè)強(qiáng)健 實(shí)用的asp+ajax二級(jí)聯(lián)動(dòng)菜單(有演示和附源程序打包下載)
- asp.net省市三級(jí)聯(lián)動(dòng)的DropDownList+Ajax的三種框架(aspnet/Jquery/ExtJs)示例
- 前臺(tái)JS(jquery ajax)調(diào)用后臺(tái)方法實(shí)現(xiàn)無(wú)刷新級(jí)聯(lián)菜單示例
- 落伍首發(fā) php+mysql 采用ajax技術(shù)的 省 市 地 3級(jí)聯(lián)動(dòng)無(wú)刷新菜單 源碼
- Ajax+Json 級(jí)聯(lián)菜單實(shí)現(xiàn)代碼
相關(guān)文章
javascript 拖動(dòng)_cookie_ajax等
比較實(shí)用的js拖動(dòng)效果代碼。類的寫(xiě)法不錯(cuò),是個(gè)不錯(cuò)的應(yīng)用2008-06-06談?wù)凙jax原理實(shí)現(xiàn)過(guò)程
Asynchronous javascript and xml(ajax),實(shí)現(xiàn)了客戶端與服務(wù)器進(jìn)行數(shù)據(jù)交流過(guò)程。使用技術(shù)的好處是:不用頁(yè)面刷新,并且在等待頁(yè)面?zhèn)鬏敂?shù)據(jù)的同時(shí)可以進(jìn)行其他操作2015-11-11解決ajax返回驗(yàn)證的時(shí)候總是彈出error錯(cuò)誤的方法
這篇文章主要介紹了解決ajax返回驗(yàn)證的時(shí)候總是彈出error錯(cuò)誤的方法,感興趣的小伙伴們可以參考一下2016-01-01ajax傳遞多個(gè)參數(shù)的實(shí)現(xiàn)代碼
這篇文章主要為大家詳細(xì)介紹了ajax傳遞多個(gè)參數(shù)的實(shí)現(xiàn)代碼,簡(jiǎn)單實(shí)用,感興趣的小伙伴們可以參考一下2016-05-05PPJOKE 0.1 (網(wǎng)頁(yè)嵌入聊天)提供下載
PPJOKE 0.1 (網(wǎng)頁(yè)嵌入聊天)提供下載...2006-10-10ajax詳解_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要介紹了ajax詳解,詳細(xì)的介紹了Ajax 簡(jiǎn)史以及 基本用法,有興趣的可以了解一下2017-07-07