經典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
- <%@ page language="java"pageEncoding="utf-8"%>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>AJAX輸入提示</title>
- <metahttp-equiv="pragma"content="no-cache">
- <metahttp-equiv="cache-control"content="no-cache">
- <metahttp-equiv
- <metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">
- <metahttp-equiv="description"content="This is my page">
- <styletype="text/css"media="screen">
- .onmouset_out {
- background-color: #99CCFF;
- padding: 2px 6px 2px 6px;
- }
- .onmouset_over {
- background-color: #006600;
- padding: 2px 6px 2px 6px;
- }
- #result_display {
- border: 1px solid #FFFFFF;
- }
- </style>
- <scripttype="text/javascript">
- var xmlHttp;
- //建立XMLHttpRequest物件
- function createXmlHttp() {
- //根據window.XMLHttpRequest物件是否存在使用不同的建立方式
- if (window.XMLHttpRequest) {
- //FireFox、Opera等瀏覽器支援的建立方式
- xmlHttp = new XMLHttpRequest();
- } else {
- //IE瀏覽器支援的建立方式
- xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
- }
- }
- function inputSuggest() {
- var txtValue = document.getElementById('txt').value;
- createXmlHttp();
- xmlHttp.onreadystatechange = _handle;
- url = "suggest.do?txtValue=" + txtValue;
- xmlHttp.open("POST", url, false);
- xmlHttp.send(null);
- }
- function _handle() {
- if(xmlHttp.readyState==4){
- if(xmlHttp.status==200){
- var str = xmlHttp.responseText.split("#");
- var s = document.getElementById('result_display')
- s.innerHTML = '';
- for(i=0; i <str.length - 1; i++) {
- var suggest = '<div onmouseover="onmouseOver(this);" ';
- suggest += 'onmouseout="onmousetOut(this);" ';
- suggest += 'onclick="setSuggestValue(this.innerHTML);" ';
- suggest += 'class="onmouset_out">' + str[i] + '</div>';
- s.innerHTML += suggest;
- }
- }
- }
- }
- function onmouseOver(div) {
- div.className = 'onmouse_over';
- }
- function onmousetOut(div) {
- div.className = 'onmouset_out';
- }
- function setSuggestValue(value) {
- document.getElementById('txt').value = value;
- document.getElementById('result_display').innerHTML = '';
- }
- </script>
- </head>
- <body>
- <h3>一個簡單的AJAX輸入提示</h3>
- <formid="frmSearch"action="">
- <inputtype="text"id="txt"name="author"alt="輸入條件"onkeyup="inputSuggest();"style="width:200px"/>
- <inputtype="submit"id="search"value="搜尋"alt="搜尋"/><br/>
- <divid="result_display"style="width:200px">
- </div>
- </form>
- </body>
- </html>
2、編寫後臺處理非同步請求的處理器,該處理器我採用的是struts1.2的action,你使用其他的(如servlet,struts2等)都一樣,下面是該action的完整程式碼:SuggestAction.java
Java程式碼- package org.hnylj.ajax.action;
- import java.io.PrintWriter;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.struts.action.Action;
- import org.apache.struts.action.ActionForm;
- import org.apache.struts.action.ActionForward;
- import org.apache.struts.action.ActionMapping;
- import org.hnylj.db.DbManager;
- /**
- * 根據前臺輸入非同步從後臺獲取資料的Action
- * @編寫者:hnylj
- *
- */
- publicclass SuggestAction extends Action {
- private DbManager dbManager;
- public ActionForward execute(ActionMapping mapping, ActionForm form,
- HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- String param = request.getParameter("txtValue");
- dbManager = new DbManager();
- String result = dbManager.searchSuggest(param);
- PrintWriter out = response.getWriter();
- out.print(result);
- out.flush();
- returnnull;
- }
- }
3.該action呼叫了一個數據庫操作類,下面是該資料庫操作類的完整程式碼:DbManager.java
Java程式碼- package org.hnylj.db;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- /**
- * 資料庫管理與操作
- * @編寫者:hnylj
- *
- */
- publicclass DbManager {
- private Connection conn;
- private Statement stmt;
- private ResultSet rs;
- privatestaticfinal String DRIVER = "com.mysql.jdbc.Driver";
- privatestaticfinal String URL = "jdbc:mysql://localhost/suggest";
- privatestaticfinal String USERNAME = "root";
- privatestaticfinal String PASSWORD = "123";
- // 資料庫連線
- publicsynchronized Connection getConnection() {
- try {
- Class.forName(DRIVER);
- conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- returnnull;
- } catch (SQLException e) {
- e.printStackTrace();
- returnnull;
- }
- return conn;
- }
- /**
- * 獲取符合輸入條件的資料
- * @param conn
- * @param sql
- * @return
- */
- public String searchSuggest(String param) {
- String sql = "select author from article where author like '" + param + "%' order by author";
- String author = "";
- String str = "";
- try {
- conn = this.getConnection();
- stmt = conn.createStatement();
- rs = stmt.executeQuery(sql);
- while (rs.next()) {
- author = rs.getString("author");
- str += author + "#";
- }
- } catch (SQLException e) {
- e.printStackTrace();
- return"";
- }
- return str;
- }
- }
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頁面程式碼有點醜陋,大家可以在其基礎上修改,也可以增強其功能,例如增加每個顯示結果的條數等!