代码是按照参考书上敲的,然后加到petstore上,弄了好久,还是要注意几个问题:
一,注意addRow(items[i].firstChild.nodeValue); 的语法,,items后面应该是中括号,书上这里写错了,照着敲了上去,弄了好久都不成功,原因就在这里。
二,row.appendChild(cell);
content.appendChild(row);
这两个代码是加在cell.οnclick=function()函数之外的,之前不细心,加在了函数之内,这也是不成功的原因。
jsp (部分):
<span style="font-size:18px;"><script type="text/javascript">
//创建XMLHttpRequest对象
function createXMLHttpRequest(){
if(window.XMLHttpRequest){
//Mozilla浏览器
XMLHttpReq=new XMLHttpRequest();
}else{
if(window.ActiveXObjct){
try{
//IE
XMLHttpReq=new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
XMLHttpReq=new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
}
}
}
}
//处理响应结果
function handleResponce(){
if(XMLHttpReq.readyState==4){
//信息成功返回,开始处理
if(XMLHttpReq.status==200){
clearTable();
var out="";
var res=XMLHttpReq.responseXML;
var rest=XMLHttpReq.responseText;
//var response=res.getElementsByTagName("response")[0].firstChild.nodeValue;
//document.getElementById("usernameInfo").innerHTML=response;
var items=res.getElementsByTagName("item");
//var items=res.getElementsByTagName("response")[0].firstChild.nodeValue;
for(var i=0;i<items.length;i++){
addRow(items[i].firstChild.nodeValue);//注意此处items后为中括号,切记!
}
setDivStyle();
}
}
}
function clearTable(){
var x=document.getElementById("content")
while(content.childNodes.length>0){
content.removeChild(content.childNodes[0]);
}
}
function addRow(item){
var content=document.getElementById("content");
var row=document.createElement("tr");
var cell=document.createElement("td");
cell.appendChild(document.createTextNode(item));
cell.οnmοuseοver=function(){this.style.background="blue";};
cell.οnmοuseοut=function(){this.style.background="#f5f5f1";};
cell.οnclick=function(){
document.getElementById("key").value=this.innerHTML;
document.getElementById("suggest").style.visibility="hidden";
};
row.appendChild(cell);
content.appendChild(row);
}
function sendRequest(url){
createXMLHttpRequest();
XMLHttpReq.open("GET",url,true);
//指定响应函数,注意这里不带括号
XMLHttpReq.onreadystatechange=handleResponce;
XMLHttpReq.send(null);
}
function setDivStyle(){
var suggest=document.getElementById("suggest");
suggest.style.border="red 1px solid";
//suggest.style.left=62;
//suggest.style.top=50;
//suggest.style.width=300;
suggest.style.backgroundColor="#f5f5f1";
document.getElementById("suggest").style.visibility="visible";
}
function suggest(){
var key=document.getElementById("key").value;
sendRequest("suggest?key="+key);
}
</script>
</head>
<body>
<div id="Header">
<div id="Logo">
<div id="LogoContent">
<a href="main"><img src="images/logo-topbar.gif" /></a>
</div>
</div>
<div id="Menu">
<div id="MenuContent">
<a href="viewCart"><img align="middle" name="img_cart" src="images/cart.gif" /></a>
<img align="middle" src="images/separator.gif" />
<a href="signonForm">Sign In</a>
<a href="signonOut">Sign Out</a>
<img align="middle" src="images/separator.gif" />
<a href="myAccount">My Account</a>
<img align="middle" src="images/separator.gif" />
<a href="../help.html">?</a>
</div>
</div>
<div id="Search">
<div id="SearchContent">
<form action="searchProduct" method="post">
<input type="text" name="keyword" id="key" οnkeyup="suggest()" size="14" />
<div id="suggest" style="position:absolute">
<table>
<tbody id="content"></tbody>
</table>
</div>
<input type="submit" name="searchProducts" value="Search" />
</form>
</div>
</div></span>
Sevlet:
package org.csu.mypetstore.web.servlets;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.csu.mypetstore.domain.Product;
import org.csu.mypetstore.service.CatalogService;
public class SuggestServlet extends HttpServlet {
/* private ArrayList lib=new ArrayList();
public void init() throws ServletException{
lib.add("a");
lib.add("able");
lib.add("abcde");
}
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// System.out.print(request.getParameter("key"));
response.setContentType("text/xml;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
response.setCharacterEncoding("utf-8");
PrintWriter out=response.getWriter();
String output="";
String key=request.getParameter("key");
ArrayList matchList=getMatchString(key);
//System.out.println(matchList.size());
out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
if(!matchList.isEmpty()){
output+="<response>";
for(int i=0;i<matchList.size();i++){
String match=matchList.get(i).toString();
output+="<item>"+match+"</item>";
}
output+="</response>";
}
else{System.out.println("错误");}
System.out.println(output);
out.println(output);
out.close();
}
public ArrayList getMatchString(String key){
// System.out.println(key);
CatalogService catalogService=new CatalogService();
ArrayList result=new ArrayList();
List<Product> productList=catalogService.searchProductList(key);
if(productList!=null){
for(int i=0;i<productList.size();i++){
String str=productList.get(i).getName().toString();
System.out.println("名字列表"+str);
if(str.startsWith(key)){
System.out.println("以A开头:"+str);
result.add(str);
}
}
}
return result;
/* ArrayList result=new ArrayList();
if(!lib.isEmpty()){
for(int i=0;i<lib.size();i++){
String str=lib.get(i).toString();
if(str.startsWith(key)){
result.add(str);
}
}
}
return result;
*/
}
}
还有一个问题不明白的就是不懂得如何定义提示框的显示位置,不能和输入框对齐,这个还在解决之中。