搜索框输入内容,动态显示提示(ajax)

搜索框输入内容,利用ajax动态显示提示

即当我们在搜索框中输入一个a时,当且仅当我们输入完a后,搜索框可以提示我们aa,或者abc等等,我们也可以选定aa,abc等等

搜索框和提示内容的处理代码:

<div align="center">
				<br>
				<form action="QueryByCondition2" method="post">
					<input type="text" size="42" name="fieldValue" placeholder="请输入关键字"
						id="inputWord" onKeyUp="search()"> 
						<input type="submit"value="搜索" name="submit">
	<div id="wordsListDiv" style="position: absolute; visibility: hidden">
						<table id="wordsListTable">
							<tbody id="wordsListTbody">
								<tr>
									<td>test</td>
								</tr>
							</tbody>
						</table>
					</div>
				</form>
				<br>
			</div>

利用ajax动态传到后台的js:

function search(){

		var inputWord = document.getElementById('inputWord').value;
        var url="SearchSuggest";
		var params = 'inputWord='+inputWord;
		sendRequest(url,params,'POST',display);			

	}

还有对后台传回数据的展示处理代码

<script type="text/javascript">
    var trSrc;
	function search(){

		var inputWord = document.getElementById('inputWord').value;
		//console.log(124);
		//console.info(234);
		//console.error(123);
		var url="SearchSuggest";
		var params = 'inputWord='+inputWord;
		sendRequest(url,params,'POST',display);			

	}
	function display(){
		if (httpRequest.readyState == 4) { 
			if (httpRequest.status == 200) {
				var xmlDoc = httpRequest.responseXML;
				clearDivData();
				changeDivData(xmlDoc);				
			} else { //页面不正常 
				alert("您请求的页面有异常"); 
			}
		}
	}
	
	//清除下拉提示框中已有的数据
	function clearDivData(){
		var tbody = document.getElementById('wordsListTbody');
		var trs = tbody.getElementsByTagName('tr');
		for(var i=trs.length-1;i>=0;i--){
			tbody.removeChild(trs[i]);
		}
	}
	
	
	//实际将数据加入下拉提示框
	function changeDivData(xmlDoc){
		var words = xmlDoc.getElementsByTagName('word');
		//var data ="{}"; //json字符串
//var obj = JSON.parse(data);
//alert(obj.rows);
	//var words=JSON.stringify(json );
	//var words=JSON.parse(json);
	//console.log(124);
	//var words=request.getAttribute("json");
		var tbody = document.getElementById('wordsListTbody');
		for(i=0;i<words.length;i++){
			var newTr = document.createElement('tr');
			var newCell = document.createElement('td');
			var wordText=words[i].firstChild.data;
			var textNode = document.createTextNode(wordText);
			newCell.onmouseover=function(){
		    //设置用户选中条目的背景色
              if(trSrc){
	               trSrc.style.backgroundColor="white";
	          }
	         trSrc=this;
	          trSrc.style.backgroundColor="gray";
			};
			newCell.onclick=setText;
			newCell.appendChild(textNode);
			newTr.appendChild(newCell);
			tbody.appendChild(newTr);
		}
		if(words.length>0){
			document.getElementById('wordsListDiv').style.visibility='visible';
		}else{
			document.getElementById('wordsListDiv').style.visibility='hidden';
		}
	}
		
	//将用户选中条目显示在文本框中
	function setText(){
	   document.getElementById('inputWord').value=trSrc.firstChild.data;
	   document.getElementById('wordsListDiv').style.visibility="hidden";
	
	}
	
	//设置下拉提示框的位置
	function setDivPosition(){
		var input = document.getElementById('inputWord');
		var listdiv = document.getElementById('wordsListDiv');
		listdiv.style.left=(input.offsetLeft)+'px';
		listdiv.style.border='blue 1px solid';
		listdiv.style.top=(input.offsetTop+input.offsetHeight ) + 'px' ;
		listdiv.style.width=input.offsetWidth+'px';
	}
</script>

 

最后是后台处理的代码:

package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

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

/**
 * Servlet implementation class SerachSuggest
 */
@WebServlet("/SearchSuggest")
public class SearchSuggest extends HttpServlet {
	/**
	 * Constructor of the object.
	 */
	

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

	public SearchSuggest() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * 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 {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out
				.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the GET method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}
public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
response.setContentType("text/xml;charset=UTF-8");
PrintWriter out = response.getWriter();
HashMap map = new HashMap();
map.put("A","<words><word>a</word><word>ab</word><word>abc</word><word>abcd</word><word>abcde</word></words>");
map.put("ab","<words><word>ab</word><word>abc</word><word>abcd</word><word>abcde</word></words>");
map.put("abc","<words><word>abc</word><word>abcd</word><word>abcde</word></words>");
map.put("abcd","<words><word>abcd</word><word>abcde</word></words>");
map.put("abcde","<words><word>abcde</word></words>");
String inputWord= request.getParameter("inputWord");
if(!map.containsKey(inputWord)){
out.println("<words></words>");
}else{
out.println(map.get(inputWord).toString());
}
}


	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}

 

考虑过一个问题,现在这个后台处理是写死的,我想要的操作是通过ajax动态查询数据库的相似内容,给予用户搜索提示,但是目前没有做到这个功能,研究了好几天,仍没有实现。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值