jquery+ajax实现像百度搜索框中输入文字

来源:互联网 发布:java创建数组的方式 编辑:程序博客网 时间:2024/06/08 12:37

通过JS的keydown事件来获得搜索栏里的关键字 再用AJAX将关键字提交到后台 返回根据该关键字得到的LIST 并转换成HTML代码 然后放到页面上

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="GBK"
contentType="text/html; charset=GBK"%>
<%
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 'index.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">
   <style>
a {
display: block;
color: #7F9DB9;
text-decoration: none;
font-size: 12px;
}

a:hover {
font-size: 12px;
color: #33AECC;
}
</style>
   <script type="text/javascript">
    function onTextChanage(keyObject){
     var keyValue = keyObject.value;
     var thisDiv = document.getElementById("detail");
    
     if(keyValue != null && keyValue != top.oldValue){
      top.oldValue = keyValue;
      keyValue = keyValue.replace(/(^\s*)/g,"");
      if(keyValue != ""){
       getResponseMeanToDiv(thisDiv,keyValue);
      }else{
       thisDiv.innerHTML = "";
       thisDiv.style.display = "none";
      }
     }
    }
   </script>
   <script type="text/javascript">
    if (window.ActiveXObject && !window.XMLHttpRequest) {
         window.XMLHttpRequest=function() {
           return new ActiveXObject((navigator.userAgent.toLowerCase().indexOf('msie 5') != -1) ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP');
        };
      }//取得XMLHttpRequest对象
     
      //将数据提交到后台并返回个HTML串
      function getResponseMeanToDiv(thisDiv,keyValue){
       var request = new XMLHttpRequest();
       if(request){
        request.onreadystatechange=function(){
        if(request.readyState == 4 && request.status == 200){
           if(request.responseText != null && request.responseText != ""){
            thisDiv.innerHTML = request.responseText;
            thisDiv.style.display = "block";
           }
         }
        }
       }
       request.open("POST", "getMean?keyValue="+ keyValue + "&randomNumber="+ 10 * Math.random(), true);
            request.setRequestHeader("text/html; charset=GBK", "application/x-www-form-urlencoded");    
           request.send("&timeStamp=" + new Date().getTime());    
//     request.open('GET',"getMean?keyValue="+ keyValue + "&randomNumber="+ 10 * Math.random());
//     request.send(null);//发送参数如果有参数req.send("username="+user_name);用request取得
      }
   </script>
</head>

<body>
   <input type="text" name="keyValue" onkeyup="onTextChanage(this)"

    style="width: 250px; height: 22px; font-size: 10pt; border-top: 1px solid #7F9DB9; border-right: 0px; border-bottom: 1px solid #7F9DB9; border-left: 1px solid #7F9DB9; border-right: 1px solid #7F9DB9;">
   <br>
   <div id="detail"
    style="width: 250px; border-bottom: 1px solid #7F9DB9; border-left: 1px solid #7F9DB9; border-right: 1px solid #7F9DB9; display: none;">

   </div>
</body>
</html>

---------------------------------------------------------------------------------------------------------------------------------

GetMeanAjax .java

package servlet;

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;

import util.Utils;

public class GetMeanAjax extends HttpServlet {

/**
* Constructor of the object.
*/
public GetMeanAjax() {
   super();
}

/**
* Destruction of the servlet. <br>
*/
public void destroy() {
   super.destroy(); // Just puts "destroy" string in log
   // Put your code here
}

/**
* 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/xml;charset=GBK");
   PrintWriter out = response.getWriter();
   String keyValue = request.getParameter("keyValue");
   String html = null;
   if (keyValue == null || keyValue.trim().equals("")) {
    html = "";
   } else {
    html = Utils.listToAJAXString(Utils.getTestList(keyValue));
   }
   try {
    out.println(html);
   } finally {
    out.flush();
    out.close();
   }
}

/**
* The doPost method of the servlet. <br>

* This method is called when a form has its tag value method equals to post.

* @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 doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   doGet(request, response);
}

public void init() throws ServletException {
   // Put your code here
}

}

-----------------------------------------------------------------------------------------------------------------------------------

Utils.java

package util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

/**
* @author Lv9
* @since 2009-8-8
*/
public class Utils {
/**
* 该方法是将LIST转换成HTML的代码 可以改

* @param list
*          需要转换的List
* @return String 转换好的HTML代码
*/
public static String listToAJAXString(List<String> list) {

   // 如果List为空则返回无内容的字符串
   if (list == null || list.isEmpty()) {
    return "";
   } else {
    StringBuffer html = new StringBuffer("");
    // 每条List都生成一条HTML
    for (Iterator<String> it = list.iterator(); it.hasNext();) {
     html.append(span.replaceAll(span_detail, it.next())); // 将span模板里的关键字替换成现有内容
    }
    return html.toString();
   }
}

/**
* 获得List方法 测试专用 方法内容:根据传进来的关键字生成一个随机长度List

* @param keyValue
*          关键字
* @return List<String> 随机长度的List
*/
public static List<String> getTestList(String keyValue) {
   List<String> list = new ArrayList<String>();
   Random random = new Random();
   int y = 0;
   while (y < 1) {
    y = random.nextInt(20);// 长度在20之间 大于0
   }
   for (int i = 0; i < y; i++) {
    list.add(keyValue + i);
   }
   return list;
}

/** 生成的模板 */
public final static String span = "<span style=\"font-size: 12px;text-overflow:ellipsis;overflow:hidden;white-space: nowrap;padding:2px;width:248px;\"><a href=\"javascript:void(0);\" onclick = \"document.getElementById('keyValue').value = this.innerHTML;document.getElementById('detail').style.display = 'none';\"> #detail#</a> </span> ";

/** 模板里的属性 */
public final static String span_detail = "#detail#";
}

--------------------------------------------------------------------------------------------------------------------------------

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>GetMeanAjax</servlet-name>
    <servlet-class>servlet.GetMeanAjax</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>GetMeanAjax</servlet-name>
    <url-pattern>/getMean</url-pattern>
</servlet-mapping>
<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

0 0
原创粉丝点击