OpenLayers學習筆記9——使用servlet與jquery-ui實現自動提示輸入,jqueryajaxservlet
做軟體都要從使用者的角度來做,怎麼樣讓使用者輸入的更少,體驗更好,我們就應該怎麼來做,也就是需求驅動,客戶都是大爺!題外話說完了,步入正題,本文實現在查詢時輸入查詢條件時,自動提示資料庫中包含改值所有記錄(注意,我這裡用的是包含,not start,not end,這是跟mysql的模糊查詢相關的),看下實現效果:
1、使用jquery ui的autocomplete控制項jQuery UI Autocomplete是jQuery UI的自動完成組件它支援本地的Array/JSON數組、通過ajax請求的Array/JSON數組、JSONP、以及Function(最靈活)等方式來擷取資料。這裡我主要採用後者:json數組。
對於JSON格式的Array,要求有:label、value屬性,如下:
[{"label":"山東省青島第二中學","value":"山東省青島第二中學"},{"label":"山東省青島第六十三中學","value":"山東省青島第六十三中學"}]其中label屬性用於顯示在autocomplete快顯功能表,而value屬性則是選中後給文字框賦的值。關於jquery ui控制項的使用可以去http://www.w3cschool.cc/jqueryui/jqueryui-tutorial.html學習它的api和用法,就不再贅述了。2、伺服器端Servlet同樣,跟前面從mysql擷取資料一樣,採用servlet來與資料庫互動,代碼如下:
public class AddressAutocompleteServlet extends HttpServlet {/** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 設定輸出內容格式和編碼response.setContentType("text/html;charset=utf-8");PrintWriter out = response.getWriter();// 設定接收參數編碼格式response.setCharacterEncoding("utf-8");// 構造sql查詢語句String schoolAddress = new String(request.getParameter("term").getBytes("ISO-8859-1"), "UTF8");String sql = "select address from school where address like " + "\'"+ "%" + schoolAddress + "%" + "\'";PoiDBBean poiDBBean = new PoiDBBean();// 查詢結果以json資料格式返回JSONArray array = new JSONArray();try {ResultSet resultSet = poiDBBean.query(sql);while (resultSet.next()) {JSONObject object = new JSONObject().element("label",resultSet.getString(1)).element("value",resultSet.getString(1));array.add(object);}out.println(array.toString());System.out.println(array.toString());} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {try {poiDBBean.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}autocomplete預設輸入的參數名為term,在瀏覽器中輸入:http://127.0.0.1:8080/taxGIS/servlet/AddressAutocompleteServlet?term=嶗山區松嶺路,會出現返回的json資料,如下:
3、用戶端使用使用的時候就很簡單了,參照api,只需幾行代碼:
$("#schoolAddress").autocomplete({ source: "http://127.0.0.1:8080/taxGIS/servlet/AddressAutocompleteServlet", minLength: 3 });部落格還是要堅持寫啊,這是總結沉澱的過程。勁量寫的調理清楚,把遇到的問題和解決方案都記錄下來,以便日後尋找,也為幫到需要的人