模拟Google自动补全功能

1 篇文章 0 订阅
 


 

 

 

模拟googlesugest自动补全功能
   首先你需要建立数据库,然后建表googlesuggest     
                                          id : integer autoincrease notnull
                                     content : text notnull(不要向里面填写汉字)
你可以先自己添加一些数据模拟一下(注意content里面先不要出现汉字)。
这里我使用的是hibernate3.1提取数据(你也可以使用其他的),hibernate自动为我建立了几个文件:其中包括GooglesuggestDAO.java 和Googlesuggest.java,另外我用的是struts1.2: 
struts-config.xml文件里面比较重要的文字:
  <action-mappings >
    <action path="/makematche" type="struts.action.MakematcheAction" />
  </action-mappings>
对应的MakematchAction.java文件:
package struts.action;
import hibernate.Googlesuggest;
import hibernate.GooglesuggestDAO;
import java.util.List;
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;
public class MakematcheAction extends Action {
 public ActionForward execute(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response) throws Exception {
  response.setContentType("text/xml;charset=UTF-8");
  response.setHeader("Cache-Control", "no-cache");
  String s = request.getParameter("param");
  GooglesuggestDAO gDao=new GooglesuggestDAO();
  Googlesuggest g=new Googlesuggest();
  List list=gDao.findLikeContent(s);
  String xml = "<?xml version=/"1.0/" encoding=/"UTF-8/"?>";
  xml += "<message>";
  for(int i=0;i<list.size();i++){
   g = (Googlesuggest) list.get(i);
   xml += "<info>" + g.getContent() + "</info>";
  }
  xml += "</message>";
  response.getWriter().write(xml);
  return null;
 }
}
用它发送xml文件到客户机上
前台文件:build.js
var arrOptions = new Array();
var strLastValue = "";
var theTextBox;
var currentValueSelected = -1;
window.onload = function () {
 var elemSpan = document.createElement("span");
 elemSpan.id = "spanOutput";
 elemSpan.className = "spanTextDropdown";
 document.body.appendChild(elemSpan);
 document.Form1.txtUserInput.onkeyup = GiveOptions;
};
function GiveOptions() {
 var intKey = -1;
 if (window.event) {
  intKey = event.keyCode;
  theTextBox = event.srcElement;
 // TypeAhead(theTextBox.value);
 }
 if (theTextBox.value.length == 0) {
  HideTheBox();
  strLastValue = "";
  return false;
 }
 if (intKey == 13) {
  GrabHighlighted();
  theTextBox.blur();
  return false;
 } else {
  if (intKey == 38) {
   MoveHighlight(-1);
   return false;
  } else {
   if (intKey == 40) {
    MoveHighlight(1);
    return false;
   }
  }
 }
 if (theTextBox.value.indexOf(strLastValue) != 0 || arrOptions.length == 0 || (strLastValue.length == 0 && theTextBox.value.length > 0) || (theTextBox.value.length <= strLastValue.length)) {
  strLastValue = theTextBox.value;
  TypeAhead(theTextBox.value);
 } else {
  BuildList(theTextBox.value);
  // strLastValue = theTextBox.value;
 }
}
function TypeAhead(xStrText) {
 var url = "makematche.do?param=" + xStrText;
 if (window.XMLHttpRequest) {
  req = new XMLHttpRequest();
 } else {
  if (window.ActiveXObject) {
   req = new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
 if (req) {
  req.open("GET", url, true);
  req.onreadystatechange = callback;
  req.send(null);
 }
}
function callback() {
 if (req.readyState == 4) {
  if (req.status == 200) {
   parseMessage();
                 // update the HTML DOM based on whether or not message is valid
  } else {
   alert("Not able to retrieve description" + req.statusText);
  }
 } else {
 }
}
function parseMessage() {
 var xmlDoc = req.responseXML.documentElement;
 var node = xmlDoc.getElementsByTagName("info");
 arrOptions = new Array();
 for (var i = 0; i < node.length; i++) {
  arrOptions[i] = node[i].firstChild.nodeValue;
 }
 BuildList(theTextBox.value);
 strLastValue = theTextBox.value;
}
function BuildList(theText) {
 SetElementPosition();
 var inner = "";
 var theMatches = MakeMatches(theText);
 for (var i = 0; i < theMatches.length; i++) {
  inner += theMatches[i];
 }
 if (theMatches.length > 0) {
  document.getElementById("spanOutput").innerHTML = inner;
  document.getElementById("OptionsList_0").className = "spanHighElement";
  currentValueSelected = 0;
 } else {
  HideTheBox();
 }
}
function SetElementPosition() {
 var selectedPosX = 0;
 var selectedPosY = 0;
 var theElement = document.Form1.txtUserInput;
 var theTextBoxInt = document.Form1.txtUserInput;
 if (!theElement) {
  return;
 }
 var theElemHeight = theElement.offsetHeight;
 var theElemWidth = theElement.offsetWidth;
 while (theElement != null) {
  selectedPosX += theElement.offsetLeft;
  selectedPosY += theElement.offsetTop;
  theElement = theElement.offsetParent;
 }
 xPosElement = document.getElementById("spanOutput");
 xPosElement.style.left = selectedPosX;
 xPosElement.style.width = theElemWidth;
 xPosElement.style.top = selectedPosY + theElemHeight;
 xPosElement.style.display = "block";
}
var countForId = 0;
function MakeMatches(xCompareStr) {
 countForId = 0;
 var matchArray = new Array();
 for (var i = 0; i < arrOptions.length; i++) {
  var regExp = new RegExp(xCompareStr, "ig");
  if ((arrOptions[i].search(regExp)) >= 0) {
   matchArray[matchArray.length] = CreateUnderline(arrOptions[i], xCompareStr, i);
  } else {
   continue;
  }
 }
 return matchArray;
}
var undeStart = "<span class='spanMatchText'>";
var undeEnd = "</span>";
var selectSpanStart = "<span/t style='width:100%;display:block;' class='spanNormalElement' οnmοuseοver='SetHighColor(this)' ";
var selectSpanEnd = "</span>";
function CreateUnderline(xStr, xTextMatch, xVal) {
 selectSpanMid = "οnclick='SetText(" + xVal + ")'" + " id='OptionsList_" + countForId + "' theArrayNumber='" + xVal + "'>";
 countForId++;
 var regExp = new RegExp(xTextMatch, "ig");
 var start = xStr.search(regExp);
 var matchedText = xStr.substring(start, start + xTextMatch.length);
 var Replacestr = xStr.replace(regExp, undeStart + matchedText + undeEnd);
 return selectSpanStart + selectSpanMid + Replacestr + selectSpanEnd;
}
function SetHighColor(theTextBox) {
 if (theTextBox) {
  currentValueSelected = theTextBox.id.slice(theTextBox.id.indexOf("_") + 1, theTextBox.id.length);
 }
 for (var i = 0; i < countForId; i++) {
  document.getElementById("OptionsList_" + i).className = "spanNormalElement";
 }
 document.getElementById("OptionsList_" + currentValueSelected).className = "spanHighElement";
}
function SetText(xVal) {
 theTextBox = document.Form1.txtUserInput;
 theTextBox.value = arrOptions[xVal]; //set text value
 document.getElementById("spanOutput").style.display = "none";
 currentValueSelected = -1; //remove the selected index
}
function GrabHighlighted() {
 if (currentValueSelected >= 0) {
  xVal = document.getElementById("OptionsList_" + currentValueSelected).getAttribute("theArrayNumber");
  SetText(xVal);
  HideTheBox();
 }
}
function HideTheBox() {
 document.getElementById("spanOutput").style.display = "none";
 currentValueSelected = -1;
}
function MoveHighlight(xDir) {
 if (currentValueSelected >= 0) {
  newValue = parseInt(currentValueSelected) + parseInt(xDir);
  if (newValue > -1 && newValue < countForId) {
   currentValueSelected = newValue;
   SetHighColor(null);
  }
 }
}
function ReDraw() {
 BuildList(document.Form1.txtUserInput.value);
}
style.css文件:
span.spanTextDropdown{ position: absolute;
top: 0px;
left: 0px;
width: 150px;
z-index: 101;
background-color: #C0C0C0;
border: 1px solid #000000;
padding-left: 2px;
overflow: visible;
display: none;
}
span.spanMatchText{ text-decoration: underline;
font-weight: bold; }
span.spanNormalElement{ background: #C0C0C0; }
span.spanHighElement{ background: #000040;
color: white;
cursor: pointer;
}
index.jsp文件:
<%@ page language="java" pageEncoding="UTF-8"%>
<html>
 <head>
  <title>Google Suggest</title>
  <style type="text/css">
<!--
@import url("style.css");
-->
</style>
  <script src="build.js" language="javascript"></script>
 </head>
 <body onResize="ReDraw()">
  <div align="center">
   <form name="Form1" AUTOCOMPLETE="off" ID="Form1">
    AutoComplete Text Box:
    <input type="text" name="txtUserInput" />
    <input type="hidden" name="txtUserValue" ID="hidden1" />
    <input type="text" name="txtIgnore" style="display:none" />
   </form>
  </div>
 </body>
</html>
 

 

 
 
 

 

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值