1. 程式人生 > >利用Ajax和JSON實現關於查詢省市名稱的二級聯動功能

利用Ajax和JSON實現關於查詢省市名稱的二級聯動功能

  功能實現的思路:我們經常碰見網上購物時候填寫收件地址會用到這個查詢省市縣的三級聯動查詢功能,我們可以利用Ajax和JSON技術模擬這個功能,說白了同樣是使用Ajax的區域性資料更新功能這個特性。因為省市都會有很多個,所以還需要使用JSONArray物件。當我們選擇某一個省的時候,會自動觸發一個區域性更新功能,這個功能的作用就是把我們選擇的關於這個省的所有市名全部在指定的位置顯示出來,當換成另外一個省的時候,還能自動把前邊的選擇的別的省所包含的市名全部刪除換成當前選擇省包含的市名。

實現步驟:

1、設計前端介面(毫無藝術感的前端介面):

 1 <body>
 2     省:
3 <select id="sheng" onchange="loadInfo()"> 4 <option value="1">河南省</option> 5 <option value="2">四川省</option> 6 <option value="3">浙江省</option> 7 <option value="4">山東省</option> 8 </select> 9 &nbsp;
10 &nbsp; 11 市: 12 <select id="shi"> 13 </select> 14 </body>

2、利用XMLHttpRequset物件放鬆請求並且接收從伺服器端傳來的處理結果:

(這裡需要注意的是新增重置操作是必要的,因為新增進JSONArray陣列的資料如果不清除的話,下一次輸出結果的時候還會輸出出來,這樣會相當於把不屬於這個省的市名也給輸出出來了,這顯然不符合設計要求)

 1 <script type="text/javascript">
 2
function loadInfo(){ 3 var shengID = document.getElementById("sheng").value; 4 //這裡要新增一個重置操作,確保每一次查詢之前JsonArray陣列是空的。 5 document.getElementById("shi").options.length=0; 6 //獲取XMLHttpRequest物件(有些瀏覽器沒有XMLHttpRequest這個物件,所以獲取之前需要先判斷一下) 7 var xmlHttp; 8 if (window.XMLHttpRequest) { 9 xmlHttp = new XMLHttpRequest(); 10 } else { 11 xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); 12 } 13 xmlHttp.onreadystatechange = function() { 14 if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { 15 //alert(xmlHttp.responseText); 16 var dataObj = eval("(" + xmlHttp.responseText + ")"); 17 for(var i=0;i<dataObj.rows.length;i++){ 18 var o=dataObj.rows[i]; 19 //利用Selectobject物件的options方法動態的新增option選項 20 document.getElementById("shi").options.add(new Option(o.text,o.id)); 21 } 22 23 } 24 } 25 xmlHttp.open("get", "getAjaxName2?shengID="+shengID, true); 26 xmlHttp.send(); 27 } 28 </script>

3、編寫處理該請求的後臺servlet程式碼:(這裡依然沒有使用資料庫查詢功能,而是手動添加了每個 省份包含的市名作為例子使用。)

 1 package com.java1234.web;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 
11 import net.sf.json.JSONArray;
12 import net.sf.json.JSONObject;
13 
14 public class GetAjaxNameServlet2 extends HttpServlet {
15 
16     /**
17      * 
18      */
19     private static final long serialVersionUID = 1L;
20 
21     @Override
22     protected void doGet(HttpServletRequest request, HttpServletResponse response)
23             throws ServletException, IOException {
24         this.doPost(request, response);
25     }
26 
27     @Override
28     protected void doPost(HttpServletRequest request, HttpServletResponse response)
29             throws ServletException, IOException {
30         response.setContentType("text/html;charset=utf-8");
31         PrintWriter out = response.getWriter();
32         //取出從前端頁面傳入的待查詢省份的shengID
33         String shengID = request.getParameter("shengID");
34         JSONObject resultJson = new JSONObject();
35         /**
36          * JSONArray物件的作用:每個省份都會有好多個市,當確認是那個省之後,
37          * 就會把每個省的所有市 的名稱包含ID全部新增進JSONArray物件中,最後再把這個包含
38          * 待查詢市的JSONArray物件當成一個物件新增進名為resultJson的JSONObject物件中。
39          */
40         JSONArray jsonArray = new JSONArray();
41         JSONObject temp = null;
42         //這裡只是模擬一下資料庫查詢操作
43         switch (Integer.parseInt(shengID)) {
44             case 1: {
45                 temp = new JSONObject();temp.put("id", 1);temp.put("text", "鄭州市");
46                 jsonArray.add(temp);                
47                 temp = new JSONObject();temp.put("id", 2);temp.put("text", "南陽市");
48                 jsonArray.add(temp);                
49                 temp = new JSONObject();temp.put("id", 3);temp.put("text", "周口市");
50                 jsonArray.add(temp);                
51                 temp = new JSONObject();temp.put("id", 4);temp.put("text", "商丘市");
52                 jsonArray.add(temp);
53                 break;
54             }
55             case 2: {
56                 temp = new JSONObject();temp.put("id", 5);temp.put("text", "成都市");
57                 jsonArray.add(temp);                
58                 temp = new JSONObject();temp.put("id", 6);temp.put("text", "綿陽市");
59                 jsonArray.add(temp);                
60                 temp = new JSONObject();temp.put("id", 7);temp.put("text", "樂山市");
61                 jsonArray.add(temp);                
62                 temp = new JSONObject();temp.put("id", 8);temp.put("text", "達州市");
63                 jsonArray.add(temp);
64                 break;
65             }
66             case 3: {
67                 temp = new JSONObject();temp.put("id", 9);temp.put("text", "杭州市");
68                 jsonArray.add(temp);                
69                 temp = new JSONObject();temp.put("id", 10);    temp.put("text", "溫州市");
70                 jsonArray.add(temp);                
71                 temp = new JSONObject();temp.put("id", 11);temp.put("text", "南通市");
72                 jsonArray.add(temp);                
73                 temp = new JSONObject();temp.put("id", 12);    temp.put("text", "寧波市");
74                 jsonArray.add(temp);
75                 break;
76             }
77             case 4: {
78                 temp = new JSONObject();temp.put("id", 13);temp.put("text", "濟南市");
79                 jsonArray.add(temp);                
80                 temp = new JSONObject();temp.put("id", 14);    temp.put("text", "青島市");
81                 jsonArray.add(temp);                
82                 temp = new JSONObject();temp.put("id", 15);temp.put("text", "泰安市");
83                 jsonArray.add(temp);                
84                 temp = new JSONObject();temp.put("id", 16);    temp.put("text", "聊城市");
85                 jsonArray.add(temp);
86                 break;
87             }
88         }
89         resultJson.put("rows", jsonArray);
90         out.println(resultJson);
91         out.flush();
92         out.close();
93     }
94 
95 }

4、配置web.xml檔案然後執行就能實現這個功能。(執行結果是一個截圖不再貼出來了,結果不重要,過程實現好了結果自然而然的不會差!)

  總結:這是一個省市查詢問題的二級聯動,相對三級聯動還算簡單一點,但這簡單的例子也是能幫助自己理解這一類問題的。這裡我按自己的理解說明一下三級聯動的實現思路:就是當我們選擇到某一個市的時候,還要再觸發一個 事件,這個事件就是要動態查詢資料庫然後把關於這個市所包含的所有縣級城市名稱全部輸出到指定的位置,當然了,這個觸發事件的實現函式還是要像查詢市級城市名稱方法一樣獲取選擇的市級城市然後作為引數傳入後臺進行查詢並把結果全部封裝到一個JSONObject物件中,然後在前端進行資料處理並進行展示。