下面我就為大家分享一篇使用Ajax和Jquery配合資料庫實現下拉框的二級連動的範例,具有很好的參考價值,希望對大家有所幫助。
首先我們需要先建立好資料庫,將一些資料插入進去
#需要兩張表:
province:省份表
city: 城市表
如圖:
然後再在java中建立相關的實體類別與之對應
再然後,我們就能開始做jdbc的操作了
public class ConnectionFactory { private static String driver; private static String url; private static String user; private static String password; static { Properties prop = new Properties(); //读取文件 try { InputStream in = ConnectionFactory.class.getResourceAsStream("./jdbc.properties"); prop.load(in); driver = prop.getProperty("jdbc.driver"); url = prop.getProperty("jdbc.url"); user = prop.getProperty("jdbc.user"); password = prop.getProperty("jdbc.password"); } catch (IOException e) { e.printStackTrace(); } } /** * 获取连接对象 * @return */ public static Connection getConnection(){ Connection conn = null; try { Class.forName(driver); conn = DriverManager.getConnection(url, user, password); } catch (Exception e) { throw new RuntimeException(e); } return conn; } /** * 关闭资源 * @param conn * @param pstmt * @param stmt * @param rs */ public static void close(Connection conn,PreparedStatement pstmt,Statement stmt,ResultSet rs){ try { if (conn != null) { conn.close(); } if (pstmt != null) { pstmt.close(); } if (stmt != null) { stmt.close(); } if (rs != null) { rs.close(); } } catch (SQLException e) { throw new RuntimeException(e); } }
首先我們可以在頁面載入的時候取得所有省份的訊息,SQL語句如下
Connection conn = null; PreparedStatement pstmt = null; Province province2 = null; @Override public ArrayList<Province> findAllPro() { ResultSet rs = null; ArrayList<Province> pros = null; try { String sql = "select id,place from province"; conn = ConnectionFactory.getConnection(); pstmt = conn.prepareStatement(sql); pros = new ArrayList<Province>(); rs = pstmt.executeQuery(); while(rs.next()){ Province province = new Province(); province.setId(rs.getInt(1)); province.setPlace(rs.getString(2)); pros.add(province); } } catch (SQLException e) { throw new RuntimeException(e); } return pros; }
將查到的資料放到後台,建立一個SelectedServlet類,用於接收查詢到的所有省份的資訊
response.setContentType("application/json;charset=utf-8"); response.setCharacterEncoding("utf-8"); request.setCharacterEncoding("utf-8"); //创建一个Place对象 ArrayList<Province> pros= new Place().findAllPro(); PrintWriter out = response.getWriter(); //将集合直接转换为Json对象 out.write(JSONArray.fromObject(pros).toString());
在這裡會用到集合轉換Json對象,我們需要導入以下幾個包
然後我們開始寫前台頁面:
<body> 省份:<select id="province"> <option>--请选择省份--</option> </select> 城市:<select id="city"> <option>--请选择城市--</option> </select> <br/><br/> <span></span> </body>
然後jQuery代碼如下:(由於我導入的jQuery版本比較低,所以使用的方法是getJSON,而不是getJson)
$.getJSON("SelectedServlet",function(data,textStatus){ var provinces = data; var res = ""; for(var i =0;i<provinces.length;i++){ <span style="white-space:pre"> </span>res += "<option>"+provinces[i].place+"</option>"; } $("#province").append(res); });
這樣就能在頁面載入的時候取得到資料
##然後我們再來做聯動,首先給下拉框添加一個change事件,然後獲取選中的信息,將選中的信息發送到另一個CityServlet中//下拉框改变时触发的事件 $("#province").change(function(){ var seled = $("option:selected").html(); $("span").html(seled); $.getJSON("CityServlet",{ "province":encodeURI(encodeURI(seled)) },function(data){ $("#city").html(""); var citys = data; var res = ""; for(var i = 0;i<citys.length;i++){ res += "<option>"+citys[i].place+"</option>"; } $("#city").append(res); }); });伺服器通過獲得的信息通過sql語句查詢出來,SQL代碼如下:
public ArrayList<City> findAllCityByPro(String name) { ResultSet rs = null; ArrayList<City> citys = null; try { //通过名字获得所有值 String sql = "select c.city_place from city c ," + "province p where c.province_id = " + " (select id from province where place = '"+ name +"') " + " and c.province_id = p.id"; conn = ConnectionFactory.getConnection(); pstmt = conn.prepareStatement(sql); citys = new ArrayList<City>(); System.out.println(sql); rs = pstmt.executeQuery(); while(rs.next()){ City city = new City(); city.setPlace(rs.getString(1)); citys.add(city); } System.out.println(citys); } catch (SQLException e) { e.printStackTrace(); } return citys; }將查詢到的數據發送到後台,後台接收到數據後將其轉換為Json對象,並通過回調函數發送到前台,然後前台就可以通過事件直接獲取到數據,而不用各種跳轉頁面,這就是Ajax(Asynchronous Javascript And XML),
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json;charset=utf-8"); response.setCharacterEncoding("utf-8"); request.setCharacterEncoding("utf-8"); // String proName = "浙江"; String proName = URLDecoder.decode(URLDecoder.decode(request.getParameter("province"), "utf-8"), "utf-8"); ArrayList<City> citys= new Place().findAllCityByPro(proName); PrintWriter out = response.getWriter(); out.write(JSONArray.fromObject(citys).toString()); }#至於顯示頁面的程式碼也在前面寫到jQuery語句中了
#效果如下:
上面是我整理給大家的,希望今後對大家有幫助。 相關文章:以上是使用Ajax和Jquery實現下拉框的二級連動的詳細內容。更多資訊請關注PHP中文網其他相關文章!