Home Web Front-end JS Tutorial Servlet+Ajax implements smart search box smart prompt function

Servlet+Ajax implements smart search box smart prompt function

Jan 01, 2018 pm 07:41 PM
accomplish search

This article mainly introduces Servlet+Ajax to realize the intelligent prompt function of the intelligent search box. Friends who are interested in ajax can refer to Servlet+Ajax to implement the intelligent prompt function of the intelligent search box

Use the refreshless technology to be intelligent Change the prompt of the search box, the same as Baidu search

Rendering

Servlet+Ajax implements smart search box smart prompt function

##The basic principle:

1. Write js binding events onkeyup (when keyboard input) and onfocus (clear the prompt when the mouse clicks outside the search box) for the search box

2. First obtain the user input, and then pass the obtained data to the server. The server passes the data to the backend, and the backend obtains the data from the server for processing, obtains the associated data, and returns json format to the front end. The front end parses the returned json into text through the callback function, and transmits the text to the display below the search box. Window

The following is the jar package that supports json

Servlet+Ajax implements smart search box smart prompt function

search.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>ajax搜索</title>
<script type="text/javascript">
//获得更多关联信息的函数
function getMore(){
 var xmlHttp;
 //首先获得用户的输入
 var content = document.getElementById("keyword");
 if(content.value==""){
  keywordBlur();//执行一下清空方法,使搜索框在无数据的时候,下方残留数据也动态清空
  return;
 }
 //alert(content.value);
 //要给服务器发送用户输入的内容,要创建对象,叫XmlHttp对象
 //xmlHttp=获得XmlHttp对象
 xmlHttp=CreatXMLHttp();
 //alert(xmlHttp);
 //要给服务器发送数据
 var url="serch?keyword="+escape(content.value);
 //如果不用escape这个函数转化一下的话,传中文会有问题
 //true表示javascript的脚本会在send()方法之后继续执行,而不会等待来自服务器的相应
 xmlHttp.open("GET",url,true);
 //xmlHttp绑定一个回调方法去接受服务器传来的相应,会在xmlHttp状态改变的时候被调用
 //xmlHttp有0~4的状态,只关心4的方法
 //4为complete状态,表示交互完成,当交互完成时才会调用回调方法
 xmlHttp.onreadystatechange=callback;
 xmlHttp.send(null);//send里面发送的是内容体,但参数在URL里已经都写完了
 //回调函数==!!注意 这里回调方法要在方法内创建,因为创建的xmlHttp对象不是全局变量
 //是在getMore()方法里创建的,可以将变量提取出来,变成全局变量
 function callback(){
  if (xmlHttp.readyState==4){
   //200代表服务器相应成功。。。404代表资源未找到。。500服务器内部错误
   if(xmlHttp.status==200){
    //交互成功,获得相应的数据,是文本格式
    var result=xmlHttp.responseText;
    //解析json格式
    var json=eval("("+result+")");//要在两边加个小括号,js才能认识
    //获得数据之后就可以开始展示了。在输入框的下边展示
    setContent(json);
   }
  }
 }
 //设置关联数据展示,参数代表的是服务器传递过来的关联数据
 function setContent(contents){
  //setLocation();//设置跟输入框一样宽度
  keywordBlur();//在每次得到值之前先清空一下之前的残留数据
  var size=contents.length;//根据关联的数据长度,来生成多少<tr>
  //设置内容
  for(var i=0;i<size;i++){
   //不用appendChild()方法是因为不同浏览器可能不兼容该方法
   var nextNode=contents[i];//代表json格式的第i个元素 
   var newRow=content_table_body.insertRow();//创建行
   var newCell=newRow.insertCell();//创建单元格
   newCell.innerHTML=contents[i];//将数据赋值给单元格
  } 
 }
}
//获得XmlHttp对象
function CreatXMLHttp(){
 //要考虑不同浏览器的写法
 //大多数浏览器使用
 var xmlHttpReq;
 if(window.XMLHttpRequest){//火狐
  xmlHttpReq=new XMLHttpRequest();
 }else{
  /* if(window.ActiveXObject){
   xmlHttpReq=neww ActiveXObject("Microsoft.XMLHTTP");
   //例如ie有很多版本,不一定能创建出来这个对象,所以要添加以下一个判断
   //换一种方法,保证创建
   if(!xmlHttp){
    xmlHttpReq=new ActiveObject("Msxml2.XMLHTTP");
   }
  } */
  //一定要如下格式写 上述格式火狐IE亲测不好使
   try { //IE
    xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
   }
   catch (e) {
    try {//IE 浏览器
     xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e) {
    }
   }
 }
 return xmlHttpReq;
}
//失去焦点的时候
function keywordBlur(){
 //要获得body的元素长度,才能知道要遍历多少次
  var contentTableBody=document.getElementById("content_table_body"); 
  var size=contentTableBody.childNodes.length; 
   //因为是删除子节点,所以是从后往前才能删,同二叉树,删除子节点
  for(var i=size-1;i>=0;i--){ 
   contentTableBody.removeChild(contentTableBody.childNodes[i]); 
  } 
  document.getElementById("popp").style.border="none"; 
}
</script>
<style type="text/css">
/* #myp{
 position: absolute;
 left:30%;
 top:50%;
 margin-left: 100px;
} */
.mouseOver{
 background: #708090;
 color: #FFFAFA;
}
.mouseOut{
 background: #FFFAFA;
 color: #000000;
}
</style>
</head>
<body>
 <p id="myp">
  <!-- 输入框 -->
  <input type="text" id="keyword" size="50" onblur="keywordBlur()" onkeyup="getMore()" onfocus="getMore()"/>
  <input type="button" value="百度一下" wise="50px">
  <!-- 下面是内容展示的区域 -->
  <p id="popp">
   <table id="contentTable" bgcolor="#FFFAFA" border="0" cellpadding="0" cellspacing="0">
    <tbody id="content_table_body">
    <!-- 这个是动态查询出来的数据显示的地方 -->
     <!-- <tr><td>ajax1</td></tr>
    <tr><td>ajax2</td></tr>
    <tr><td>ajax3</td></tr> -->
    </tbody>
   </table>
  </p>
 </p>
</body>
</html>
Copy after login


SearchServlet.class


package com.ninka;
import java.io.IOException;
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 net.sf.json.JSONArray;
public class SearchServlet extends HttpServlet{
 static List<String> datas = new ArrayList<String>();
 static{
  datas.add("ajax1");
  datas.add("ajax2");
  datas.add("ajax3");
  datas.add("bichi1");
  datas.add("bichi2");
  datas.add("php"); 
  datas.add("javascript"); 
  datas.add("java"); 
  datas.add("html"); 
 }
 @Override
 protected void doGet(HttpServletRequest request, HttpServletResponse response) 
   throws ServletException, IOException {
  //设置下编码格式
  request.setCharacterEncoding("UTF-8");
  response.setCharacterEncoding("UTF-8");
  System.out.println("123");
  //首先获得客户端传来的数据,,注意传过来的参数关键字一定要写对,否则会空指针异常
  String keyword = request.getParameter("keyword");
  //获得关键字之后进行处理,得到关联数据
  List<String> listData = getData(keyword);
  //返回json格式
  System.out.println(JSONArray.fromObject(listData));
  //JSONArray.fromObject(listData);
  response.getWriter().write(JSONArray.fromObject(listData).toString());
 }
 //获得关联数据方法
 public List<String> getData(String keyword){
  List<String> list = new ArrayList<String>();
  for(String data:datas){
   //如果传递过来的数据,属于词库里面的话,那么就把包含关键词的数据打包成list,向客户端传
   if(data.contains(keyword)){
    list.add(data);
   }
  }
  return list;
 }
}
Copy after login


##web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
 http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
 id="WebApp_ID" version="3.1">
 <display-name>ajaxtest</display-name>
 <welcome-file-list>
  <welcome-file>search.jsp</welcome-file>
 </welcome-file-list>
 <servlet>
 <!-- 为什么要用search?因为在js中定义url的时候写的是search -->
  <servlet-name>search</servlet-name>
  <servlet-class>com.ninka.SearchServlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>search</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>
</web-app>
Copy after login


The above is the Servlet+Ajax implementation of the smart search box smart prompt function introduced by the editor. I hope it will be helpful to everyone! !

Related recommendations:

Detailed example of the principle of Ajax cross-domain request

Detailed explanation of Ajax and node.js multer to implement the file upload function

About the implementation method of loading waiting effect before Ajax returns data

The above is the detailed content of Servlet+Ajax implements smart search box smart prompt function. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to search for users in Xianyu How to search for users in Xianyu Feb 24, 2024 am 11:25 AM

How does Xianyu search for users? In the software Xianyu, we can directly find the users we want to communicate with in the software. But I don’t know how to search for users. Just view it among the users after searching. Next is the introduction that the editor brings to users about how to search for users. If you are interested, come and take a look! How to search for users in Xianyu? Answer: View details among the searched users. Introduction: 1. Enter the software and click on the search box. 2. Enter the user name and click Search. 3. Select [User] under the search box to find the corresponding user.

How to use Baidu advanced search How to use Baidu advanced search Feb 22, 2024 am 11:09 AM

How to use Baidu Advanced Search Baidu search engine is currently one of the most commonly used search engines in China. It provides a wealth of search functions, one of which is advanced search. Advanced search can help users search for the information they need more accurately and improve search efficiency. So, how to use Baidu advanced search? The first step is to open the Baidu search engine homepage. First, we need to open Baidu’s official website, which is www.baidu.com. This is the entrance to Baidu search. In the second step, click the Advanced Search button. On the right side of the Baidu search box, there is

How to implement dual WeChat login on Huawei mobile phones? How to implement dual WeChat login on Huawei mobile phones? Mar 24, 2024 am 11:27 AM

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

PHP Programming Guide: Methods to Implement Fibonacci Sequence PHP Programming Guide: Methods to Implement Fibonacci Sequence Mar 20, 2024 pm 04:54 PM

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

WPS table cannot find the data you are searching for, please check the search option location WPS table cannot find the data you are searching for, please check the search option location Mar 19, 2024 pm 10:13 PM

In the era dominated by intelligence, office software has also become popular, and Wps forms are adopted by the majority of office workers due to their flexibility. At work, we are required not only to learn simple form making and text entry, but also to master more operational skills in order to complete the tasks in actual work. Reports with data and using forms are more convenient, clear and accurate. The lesson we bring to you today is: The WPS table cannot find the data you are searching for. Why please check the search option location? 1. First select the Excel table and double-click to open it. Then in this interface, select all cells. 2. Then in this interface, click the &quot;Edit&quot; option in &quot;File&quot; in the top toolbar. 3. Secondly, in this interface, click &quot;

How to search for stores on mobile Taobao How to search for store names How to search for stores on mobile Taobao How to search for store names Mar 13, 2024 am 11:00 AM

The mobile Taobao app software provides a lot of good products. You can buy them anytime and anywhere, and everything is genuine. The price tag of each product is clear. There are no complicated operations at all, making you enjoy more convenient shopping. . You can search and purchase freely as you like. The product sections of different categories are all open. Add your personal delivery address and contact number to facilitate the courier company to contact you, and check the latest logistics trends in real time. Then some new users are using it for the first time. If you don’t know how to search for products, of course you only need to enter keywords in the search bar to find all the product results. You can’t stop shopping freely. Now the editor will provide detailed online methods for mobile Taobao users to search for store names. 1. First open the Taobao app on your mobile phone,

How to implement the WeChat clone function on Huawei mobile phones How to implement the WeChat clone function on Huawei mobile phones Mar 24, 2024 pm 06:03 PM

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

How to implement exact division operation in Golang How to implement exact division operation in Golang Feb 20, 2024 pm 10:51 PM

Implementing exact division operations in Golang is a common need, especially in scenarios involving financial calculations or other scenarios that require high-precision calculations. Golang's built-in division operator "/" is calculated for floating point numbers, and sometimes there is a problem of precision loss. In order to solve this problem, we can use third-party libraries or custom functions to implement exact division operations. A common approach is to use the Rat type from the math/big package, which provides a representation of fractions and can be used to implement exact division operations.

See all articles