一个通用的ajax程序(实现像百度一样自动提示功能)
1.jsp+javabean实现ajax
(1),<script type="text/javascript">
String.prototype.trim=function(){
return this.replace(/(^\s*)|(\s*$)/g, "");
}
//表名ajax
function ajaxTable(){
var table_name=document.validateRule01.table_name.value;
if(table_name==""){
document.getElementById("result_display").style.visibility='hidden';
return;
}
var X = new ActiveXObject("MSXML2.XMLHTTP.3.0");
//var X = new XMLHttpRequest();
if(X)
{
X.onreadystatechange=function(){
if(X.readyState==4)
{
if(X.status==200)
{
var mobanhtml=X.responseText;
mobanhtml=mobanhtml.trim();
var tableNames = mobanhtml.split(",");
var s = document.getElementById('result_display') ;
s.innerHTML = '';
if(tableNames.length>0){
document.getElementById('result_display').style.visibility='visible';
for(i=0; i < tableNames.length ; i++) {
var suggest = '<div onmouseover="onmouseOver(this);" ';
suggest += 'onmouseout="onmousetOut(this);" ';
suggest += 'onclick="setSuggestValue(this.innerHTML);" ';
suggest += 'class="onmouset_out">' + tableNames[i] + '</div>';
s.innerHTML += suggest;
}
}
}
else
{
}
}
};
X.open("POST","getTableName.jsp?table_name="+table_name,true);
X.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
X.send();
}
else
{
alert("??");
}
}
function onmouseOver(div) {
div.className = 'onmouse_over';
}
function onmousetOut(div) {
div.className = 'onmouset_out';
}
function setSuggestValue(value) {
document.validateRule01.table_name.value = value;
document.getElementById('result_display').innerHTML = '';
document.getElementById("result_display").style.visibility='hidden';
} 其中红色部分是要修改的部分,其他代码可以照搬
然后是促发这个ajax的text框代码:<input type='text' size='30' style="width:200px" id="txt" name='table_name' value='<%=InitBean.getTable_name()%>' onkeyup="ajaxTable();" >
在这个text框所在的table外面添加<div id="result_display" style="position:absolute; visibility:hidden; overflow:auto; top:70px; left:195px; width:200px; height:200px; background-color:#ffffff;">
</div>
2.下面是getTableName.jsp的代码:
<%@ page contentType="text/html;charset=gb2312" %>
<%@ page language="java"
session="true"
buffer="32kb"
autoFlush="true"
%>
<%@ page import="
com.hoperun.bi.quality.GetTableName,
java.sql.Connection,
java.sql.Statement,
java.sql.ResultSet
"
%>
<%--
response.setHeader("Cache-Control","no-cache"); //Forces caches to obtain a new copy of the page from the origin server
response.setHeader("Cache-Control","no-store"); //Directs caches not to store the page under any circumstance
response.setDateHeader("Expires", 0); //Causes the proxy cache to see the page as "stale"
response.setHeader("Pragma","no-cache"); //HTTP 1.0 backward compatibility
--%>
<%
String table_name=request.getParameter("table_name");
GetTableName getTableName=new GetTableName();
String str=getTableName.getTableNames(table_name);
out.write(str);
%>
3.下面是GetTableName.java的bean代码:
/*
* com.hoperun.bi.beans.SqlEditorBean0101.java
*
* Created on 2006-5-22 14:16:59
*
* Version 1.0.0
*
* Copyright 2003-2005 by NanJing HopeRun(IT-FOREST) Information System Co., Ltd, CHINA and
* IT Forest Corporation
* All rights reserved.
*
* This software is the confidential and proprietary information of
* HopeRun(IT-FOREST) Information System Co., Ltd, CHINA and IT Forest Corporation.
* You shall not disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into with
* HopeRun(IT-FOREST) Information System Co., Ltd, CHINA and IT Forest Corporation.
*/
package com.hoperun.bi.quality;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.webpump.sdk.datasource.DataSourceManager;
/**
* @author wei_yuhong
*
* 表格中文描述和字段描述定义画面Bean,选择数据源分别编辑
*/
public class GetTableName {
private Connection conn;
public GetTableName() throws SQLException{
conn=DataSourceManager.findDataSource("").getConnection();
}
/**
* 执行添加、查询等动作的过程。
* @param objIn 保存有执行此操作所需的所有数据
* @param objOut 保存查询等操作的结果数据
*/
public String getTableNames(String table_name) throws SQLException {
String str="";
try{
String sqlmodel = "select t.table_en_name from hpbi_tablestorage t where t.table_en_name like '"+table_name+"%' order by t.table_en_name";
Statement pStmt = this.conn.createStatement();
ResultSet rsmodel = pStmt.executeQuery(sqlmodel);
while(rsmodel.next()){
str+=rsmodel.getString("table_en_name")+",";
}
}catch(Exception e){
System.out.print(e);
}finally{
try {
if (conn!=null) {
conn.close();
conn = null;
}
} catch (Exception e) {
}
}
return str;
}
}
这样就可以在输入框中输入表名的首字母,就可以自动提示所有以这个字母开头的表名
二.用struts2.0的实现:只要把X.open("POST","getTableName.jsp?table_name="+table_name,true);
中的。getTableName.jsp改成getTableName.action就ok了,还有就是下面的getTableName.action的代码:
package com.hoperun.action;
import java.io.PrintStream;
import java.util.HashMap;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.hoperun.service.GetCloseIdService;
import com.hoperun.service.SalesSearchService;
import com.opensymphony.xwork2.ActionSupport;
public class getCloseIdAction extends ActionSupport
{
/** *//**
*
*/
private static final long serialVersionUID = 1L;
/**//*
*/
private GetCloseIdService getCloseIdService=new GetCloseIdService();
private String clothesid="";
public String getClothesid() {
return clothesid;
}
public void setClothesid(String clothesid) {
this.clothesid = clothesid;
}
@Override
public void validate()
{
}
@Override
public String execute() throws Exception
{
HashMap<String,String> hmInput = new HashMap<String,String>();
String reStr=getCloseIdService.getclothesIds(clothesid);
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html;charset=GBK");//解决中文乱码
PrintStream out = new PrintStream(response.getOutputStream());//获取out输出对象
out.println(reStr);
return null;//这里返回的是null
}
}
注意这里action返回的是null,千万记住