How to create smart search box prompt function with Ajax
This time I will show you how to make a smart search box prompt function with Ajax. What are the precautions for Ajax to make a smart search box prompt function? Here is a practical case, let’s take a look.
Use refresh-free technology to intelligently change the prompt of the search box, the same as Baidu search
Rendering
The basic principle:
1. Write js binding events for the search box onkeyup (when keyboard input) and onfocus (clear the prompt when the mouse clicks outside the search box)
2. First get the user After input, the obtained data is passed to the server, and the server passes the data to the background. The background obtains the data from the server for processing, obtains the associated data, and returns the json format to the front end. The front end passes the callback function to The returned json is parsed into text, and the text is transferred to the display window below the search box
The following is a jar package that supports json
search.jsp
nbsp;html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <title>ajax搜索</title> <script> //获得更多关联信息的函数 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> /* #myp{ position: absolute; left:30%; top:50%; margin-left: 100px; } */ .mouseOver{ background: #708090; color: #FFFAFA; } .mouseOut{ background: #FFFAFA; color: #000000; } </style> <p> <!-- 输入框 --> <input> <input> <!-- 下面是内容展示的区域 --> </p><p> </p>
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; } }</string></string></string></string></string></string>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app> <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>
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!
Recommended reading:
How to implement the ajax verification function using the SSM integration framework
How to implement the form with PHP+Ajax Live editing
The above is the detailed content of How to create smart search box prompt function with Ajax. For more information, please follow other related articles on the PHP Chinese website!

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Linux new version
SublimeText3 Linux latest version

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver CS6
Visual web development tools