1. 程式人生 > >經典ajax例項-ajax實現輸入時的自動提示jsp(轉)

經典ajax例項-ajax實現輸入時的自動提示jsp(轉)

ajax技術從2005年就開始流行了起來,主要是這種技術能給使用者帶來更好的瀏覽體驗,能建立更豐富的web頁面,現在的專案開發中或多或少都用了ajax技術。  

先概括性地介紹一下ajax,ajax是Asynchronous JavaScript and XML(以及 DHTML 等)的縮寫。Ajax提供與伺服器非同步通訊的能力,藉助於Ajax技術,可以非同步地向伺服器發出請求,以執行更新或查詢資料庫。當請求返回時,就可以使用JavaScript和CSS來相應地更新頁面,而不是重新整理整個頁面。最重要的是,使用者甚至不知道瀏覽器正在與伺服器通訊,Web站點看起來好象是即時響應的。

Ajax的核心是JavaScript物件XmlHttpRequest。該物件在Internet Explorer 5中首次引入,它是一種支援非同步請求的技術。簡而言之,XmlHttpRequest使您可以使用JavaScript向伺服器提出請求並處理響應。

下面是本人使用ajax實現的一個簡單例子,該例項實現了輸入時的自動提示,類似於google輸入時的提示。

基本思路是:前臺輸入查詢條件,在輸入的同時觸發一個javascript事件,該事件建立一個XMLHttpRequest物件並異步向伺服器提交請求,伺服器端收到請求後執行資料庫查詢,將查詢得到的資料以字串的形式返回至客戶端瀏覽器,然後將該字串在客戶端瀏覽器顯示。

按照如下的步驟進行:
1、編寫一個jsp頁面,在這個頁面中有一個輸入框,當用戶在該輸入框中輸入了一個字元之後,在輸入框下方將自動顯示符合輸入條件的從資料庫中查詢出來的值。下面是該jsp頁面的完整程式碼:index.jsp

Html程式碼
複製程式碼
  1. <%@ page language="java"pageEncoding="utf-8"%>
  2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  3. <html>
  4. <head>
  5. <title>AJAX輸入提示</title>
  6. <metahttp-equiv="pragma"content="no-cache">
  7. <metahttp-equiv="cache-control"content="no-cache">
  8. <metahttp-equiv
    ="expires"content="0">
  9. <metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">
  10. <metahttp-equiv="description"content="This is my page">
  11. <styletype="text/css"media="screen">
  12.      .onmouset_out {   
  13.        background-color: #99CCFF;   
  14.        padding: 2px 6px 2px 6px;   
  15.      }   
  16.      .onmouset_over {    
  17.        background-color: #006600;   
  18.        padding: 2px 6px 2px 6px;   
  19.      }   
  20.      #result_display {   
  21.        border: 1px solid #FFFFFF;      
  22.      }     
  23. </style>
  24. <scripttype="text/javascript">
  25.       var xmlHttp;    
  26.       //建立XMLHttpRequest物件   
  27.       function createXmlHttp() {   
  28.       //根據window.XMLHttpRequest物件是否存在使用不同的建立方式   
  29.         if (window.XMLHttpRequest) {   
  30.            //FireFox、Opera等瀏覽器支援的建立方式   
  31. xmlHttp = new XMLHttpRequest();    
  32.         } else {   
  33.            //IE瀏覽器支援的建立方式   
  34. xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");   
  35.         }   
  36.       }   
  37.       function inputSuggest() {   
  38.          var txtValue = document.getElementById('txt').value;   
  39.          createXmlHttp();   
  40. xmlHttp.onreadystatechange = _handle;   
  41. url = "suggest.do?txtValue=" + txtValue;   
  42.          xmlHttp.open("POST", url, false);   
  43.          xmlHttp.send(null);   
  44.       }   
  45.       function _handle() {   
  46.          if(xmlHttp.readyState==4){   
  47.             if(xmlHttp.status==200){   
  48.                 var str = xmlHttp.responseText.split("#");   
  49.                 var s = document.getElementById('result_display')   
  50. s.innerHTML = '';   
  51.                 for(i=0; i <str.length - 1; i++) {   
  52.                    var suggest = '<div onmouseover="onmouseOver(this);" ';   
  53.                    suggest += 'onmouseout="onmousetOut(this);" ';   
  54.                    suggest += 'onclick="setSuggestValue(this.innerHTML);" ';   
  55.                    suggest += 'class="onmouset_out">' + str[i] + '</div>';   
  56.                    s.innerHTML += suggest;   
  57.                 }   
  58.             }   
  59.          }   
  60.       }   
  61.       function onmouseOver(div) {   
  62. div.className = 'onmouse_over';   
  63.       }   
  64.       function onmousetOut(div) {   
  65. div.className = 'onmouset_out';   
  66.       }   
  67.       function setSuggestValue(value) {   
  68.          document.getElementById('txt').value = value;   
  69.          document.getElementById('result_display').innerHTML = '';   
  70.       }   
  71. </script>
  72. </head>
  73. <body>
  74. <h3>一個簡單的AJAX輸入提示</h3>
  75. <formid="frmSearch"action="">
  76. <inputtype="text"id="txt"name="author"alt="輸入條件"onkeyup="inputSuggest();"style="width:200px"/>
  77. <inputtype="submit"id="search"value="搜尋"alt="搜尋"/><br/>
  78. <divid="result_display"style="width:200px">
  79. </div>
  80. </form>
  81. </body>
  82. </html>

2、編寫後臺處理非同步請求的處理器,該處理器我採用的是struts1.2的action,你使用其他的(如servlet,struts2等)都一樣,下面是該action的完整程式碼:SuggestAction.java

Java程式碼 複製程式碼
  1. package org.hnylj.ajax.action;   
  2. import java.io.PrintWriter;   
  3. import javax.servlet.http.HttpServletRequest;   
  4. import javax.servlet.http.HttpServletResponse;   
  5. import org.apache.struts.action.Action;   
  6. import org.apache.struts.action.ActionForm;   
  7. import org.apache.struts.action.ActionForward;   
  8. import org.apache.struts.action.ActionMapping;   
  9. import org.hnylj.db.DbManager;   
  10. /**  
  11.  * 根據前臺輸入非同步從後臺獲取資料的Action  
  12.  * @編寫者:hnylj  
  13.  *  
  14.  */
  15. publicclass SuggestAction extends Action {   
  16. private DbManager dbManager;   
  17. public ActionForward execute(ActionMapping mapping, ActionForm form,   
  18.             HttpServletRequest request, HttpServletResponse response)   
  19. throws Exception {   
  20.         String param = request.getParameter("txtValue");   
  21.         dbManager = new DbManager();   
  22.         String result = dbManager.searchSuggest(param);   
  23.         PrintWriter out = response.getWriter();   
  24.         out.print(result);   
  25.         out.flush();   
  26. returnnull;   
  27.     }   
  28. }  

3.該action呼叫了一個數據庫操作類,下面是該資料庫操作類的完整程式碼:DbManager.java

Java程式碼 複製程式碼
  1. package org.hnylj.db;   
  2. import java.sql.Connection;   
  3. import java.sql.DriverManager;   
  4. import java.sql.ResultSet;   
  5. import java.sql.SQLException;   
  6. import java.sql.Statement;   
  7. /**  
  8.  * 資料庫管理與操作  
  9.  * @編寫者:hnylj  
  10.  *  
  11.  */
  12. publicclass DbManager {   
  13. private Connection conn;   
  14. private Statement stmt;   
  15. private ResultSet rs;   
  16. privatestaticfinal String DRIVER = "com.mysql.jdbc.Driver";   
  17. privatestaticfinal String URL = "jdbc:mysql://localhost/suggest";   
  18. privatestaticfinal String USERNAME = "root";   
  19. privatestaticfinal String PASSWORD = "123";   
  20. // 資料庫連線
  21. publicsynchronized Connection getConnection() {   
  22. try {   
  23.             Class.forName(DRIVER);   
  24.             conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);   
  25.         } catch (ClassNotFoundException e) {   
  26.             e.printStackTrace();   
  27. returnnull;   
  28.         } catch (SQLException e) {   
  29.             e.printStackTrace();   
  30. returnnull;   
  31.         }   
  32. return conn;   
  33.     }   
  34. /**  
  35.      * 獲取符合輸入條件的資料  
  36.      * @param conn  
  37.      * @param sql  
  38.      * @return  
  39.      */
  40. public String searchSuggest(String param) {   
  41.         String sql = "select author from article where author like '" + param + "%' order by author";   
  42.         String author = "";   
  43.         String str = "";   
  44. try {   
  45.             conn = this.getConnection();   
  46.             stmt = conn.createStatement();   
  47.             rs = stmt.executeQuery(sql);   
  48. while (rs.next()) {   
  49.                 author = rs.getString("author");   
  50.                 str += author + "#";   
  51.             }   
  52.         } catch (SQLException e) {   
  53.             e.printStackTrace();   
  54. return"";   
  55.         }   
  56. return str;   
  57.     }   
  58. }   

4.整個應用你還需要其他的一些配置:
 (1). 資料庫表(使用mysql):

  create database suggest;
  use suggest;

  create table article (  
     stu_id integer auto_increment,
     author varchar(30) not null,  
     title varchar(50) not null,  
     primary key(stu_id)  
  );  

  insert into article(author,title) values('hnylj','ajax');
  insert into article(author,title) values('hylj','java');
  insert into article(author,title) values('hxycj','struts');
  insert into article(author,title) values('hzyhj','hibernate');
  insert into article(author,title) values('haykj','spring');
  insert into article(author,title) values('hkyth','oracle');
  insert into article(author,title) values('hlyyi','lucence'); 

(2).保證struts程式正常執行所需要的其他配置,在這裡不一以列出,你可以下載我提供的附件,該附件是一個完整的可以執行的程式。

jsp頁面程式碼有點醜陋,大家可以在其基礎上修改,也可以增強其功能,例如增加每個顯示結果的條數等!