Ajax 模糊查询的简单实现

前端之家收集整理的这篇文章主要介绍了Ajax 模糊查询的简单实现前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

类似于百度搜索引擎模糊查询功能,不过百度的模糊查询功能更强大,这里简单实现下.

要实现模糊查询,首先要做的就是把sql写好。话不多少,直接贴代码了!

JSP页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'search.jsp' starting page</title>
    
	<Meta http-equiv="pragma" content="no-cache">
	<Meta http-equiv="cache-control" content="no-cache">
	<Meta http-equiv="expires" content="0">    
	<Meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<Meta http-equiv="description" content="This is my page">  
    <script type="text/javascript" src="prototype.js"></script>
    
    <style type="text/css">
       body{font:11px arial;}
       #suggest{
                position:absolute;
                background-color:#FFFFFF;
                text-align: :left;
                border: 1px solid #000000;
                display: none;
       }
    </style>
	<script type="text/javascript">
	    function searchSuggest(){
	    	var url="Search";
	    	var txtSearch=$F("txtSearch");
	    	var pars='txtSearch='+txtSearch;
	    	var searchAjax=new Ajax.Request(
	    	      url,{
	    	    	 method:'get',//get方式提交
	    	    	 parameters:pars,//提交参数
	    	    	 onComplete:processRequest
	    	      }
	    	);
	    }
	    function processRequest(req){
	    	var sobj=$("suggest");
	    	sobj.innerHTML="";
	    	var str=req.responseText.split("-");
	    	var suggest="";
	    	if(str.length>0&&str[0].length>0){
                for(i=0;i<str.length;i++){
                	suggest+="<div>"+str[i]+"</div>";
                }
                sobj.innerHTML=suggest;
                $("suggest").style.display="block";
	    	}else{
	    		$("suggest").style.display="none";
	    	}
	    }
	</script>
  </head>
  <body>
       <h3>Ajax自动搜索提示</h3>
       <div style="width:500px">
          <form action="" id="formSearch">
             <input type="text" id="txtSearch" name="txtSearch"  onkeyup="searchSuggest()"autocomplete="off"/>
             <input type="submit" id="cmdSerach" name="cmdSearch" value="搜索"/><br/>
             <div id="suggest" style="width:200px"></div>
          </form>
       </div>
  </body>
</html>


Sevlet类:

package servlet.ajax;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Search extends HttpServlet {

	public void doGet(HttpServletRequest request,HttpServletResponse response)
			throws ServletException,IOException {

          request.setCharacterEncoding("UTF-8");
          response.setCharacterEncoding("UTF-8");
          String req=request.getParameter("txtSearch");
          PrintWriter out = response.getWriter();
          SearchDao sd=new SearchDao();
          sd.getText(req);
          StringBuffer sb=sd.getText(req);
          out.print(sb.toString());
          out.flush();
	}
}


进行连接数据库,模糊查询的JAVA类:

package servlet.ajax;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.sqlException;
import java.util.ArrayList;
import java.util.List;

public class SearchDao {
	
	public StringBuffer  getText(String req){
		//首先定义下连接数据的URL、用户名、密码
		String url="jdbc:oracle:thin:@127.0.0.1:1521:orcl";
		String user="scott";
		String password="yulei123";
		String sql="select ename from emp a where a.ename like ?";
		if(req.trim().length()==0){
	      sql=sql+" and 1<>1";
		}
		List strList=new ArrayList();
		 try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			Connection con=DriverManager.getConnection(url,user,password);
			PreparedStatement pre=con.prepareStatement(sql);
			pre.setString(1,"%"+req.toUpperCase().trim()+"%");
			ResultSet rs=pre.executeQuery();
			while(rs.next()){
				String ename=rs.getString("ename");
				strList.add(ename);
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (sqlException e) {
			e.printStackTrace();
		}
		StringBuffer sb=new StringBuffer();
		int size=strList.size();
		for(int i=0;i<size;i++){
			sb.append((String)strList.get(i)+"-");
		}
		return sb;
	}
}


代码写好后,就可以在文本框输入字母后就可以模糊查询出数据了!

原文链接:https://www.f2er.com/ajax/165374.html

猜你在找的Ajax相关文章