We all know that Baidu recommends using ajax. It is not easy to make it fast, stable, replicable and portable. After searching online for a long time, many of them are asp or php, and some use jquery, but there are too few explanatory documents. It is better to write it yourself than to spend time on research. Based on the information provided by a pdf document, it took half a day to finally achieve it. Share it with everyone here.
The principle flow chart is as follows:
The flow chart is very clear, there is nothing to say, here is the code.
Javascript code:
var xmlHttpRequest; var table; var tbody; var div; var input; var curIndex; var size; var r_userId; function createXMLHttpRequest(){ if(window.ActiveXObject){ xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP"); }else if(window.XMLHttpRequest){ xmlHttpRequest = new XMLHttpRequest(); } } //发送请求 function findNames(){ if(event.keyCode==38||event.keyCode==40){ }else{ if(input.value.length>0){ createXMLHttpRequest(); var url = encodeURI(encodeURI("/jforum.html?module=posts&action=findDept&names="+input.value)); xmlHttpRequest.open("GET",url,true); xmlHttpRequest.onreadystatechange=processMatchResponse; xmlHttpRequest.send(null); }else{ clearNames(); } } } function processMatchResponse(){ if(xmlHttpRequest.readyState==4){ if(xmlHttpRequest.status==200){ //alert(xmlHttpRequest.status); //var id = xmlHttpRequest.responseXML.getElementsByTagName("id"); var dept = xmlHttpRequest.responseXML.getElementsByTagName("dept"); var id = xmlHttpRequest.responseXML.getElementsByTagName("id"); setNames(dept,id); }else{ window.alert("您所请求的页面有异常!"); } } } function setNames(depts,ids){ clearNames(); size = depts.length; if(size>0){ div.style.visibility = "visible"; var row,col1,col2,span; for(var i = 0;i < size;i++){ row = document.createElement("tr"); col1 = document.createElement("td"); col1.innerText = depts[i].firstChild.data; col2 = document.createElement("td"); col2.setAttribute("align","right"); col2.setAttribute("id","col2"); col2.setAttribute("width","5%"); span = document.createElement("span"); span.innerText = ids[i].firstChild.data; span.style.display = "none"; col2.appendChild(span); row.appendChild(col1); row.appendChild(col2); row.onmouseout = function(){ this.className = 'mouseOut'; } row.onmouseover = function(){ clearSelected(); this.className = 'mouseOver'; curIndex = this.rowIndex; } row.onclick = function(){ input.value = this.cells[0].innerText; r_userId.value = table.rows[curIndex].cells[1].innerText; clearNames(); }; tbody.appendChild(row); } row = document.createElement("tr"); col2 = document.createElement("td"); col1 = document.createElement("td"); col2.setAttribute("align","right"); link = document.createElement("a"); link.href = "javascript:clearNames();"; link.innerHTML = "关闭"; col1.appendChild(link); row.appendChild(col1); row.appendChild(col2); tbody.appendChild(row); } } function setPosition(){ input = document.getElementById("names"); r_userId = document.getElementById("r_userId"); table = document.getElementById("table"); div = document.getElementById("div"); tbody = document.getElementById("tbody"); div.style.width = input.offsetWidth-2; div.style.border = "gray 1px solid"; div.style.left = getLeft(input); div.style.top = getTop(input)+input.offsetHeight+6; curIndex = -1; input.focus();//div.style.left+","+div.style.top } function clearNames(){ var ind = tbody.childNodes.length; for(i=ind-1;i>=0;i--){ tbody.removeChild(tbody.childNodes[i]); } div.style.visibility="hidden"; curIndex = -1; } function clearSelected(){ var ind = tbody.childNodes.length; for(var i = ind-1;i>=0;i--){ tbody.childNodes[i].className = "mouseOut"; } } function keyDown(){ if(div.style.visibility=="visible"){ if(event.keyCode ==38){ if(curIndex>=0){ table.rows[curIndex].className='mouseOut'; curIndex = curIndex-1; if(curIndex>=0){ table.rows[curIndex].className = 'mouseOver'; input.value = table.rows[curIndex].cells[0].innerText; r_userId.value = table.rows[curIndex].cells[1].innerText; } } } if(event.keyCode==40){ if(curIndex<size-1){ if(curIndex>=0){ table.rows[curIndex].className = 'mouseOut'; } curIndex = curIndex+1; table.rows[curIndex].className = 'mouseOver'; input.value = table.rows[curIndex].cells[0].innerText; r_userId.value = table.rows[curIndex].cells[1].innerText; }else{ table.rows[curIndex].className = 'mouseOut'; curIndex = -1; } } } } //获取元素的纵坐标 function getTop(e){ var offset=e.offsetTop; if(e.offsetParent!=null) offset+=getTop(e.offsetParent); return offset; } //获取元素的横坐标 function getLeft(e){ var offset=e.offsetLeft; if(e.offsetParent!=null) offset+=getLeft(e.offsetParent); return offset; }
There are too many codes, a bit messy, and jquery is not used, but it can better show the author's skills. The following points are explained:
1, setPosition() is used to initialize various variables required globally, so it must be called first when the page is loaded, such as in the onload method of the body, or other methods.
2. findNames() is a method of operating ajax. Anyone familiar with ajax can understand that the most important thing is to re-encode the parameters encodeURI(), and correspondingly decode them in the background.
3. processMatchResponse() is a callback function used to process the data returned from the background. This is handled by setNames().
4, setNames uses table mode to display the content of the prompt. Here is more knowledge about JS and node.
5. The getTop and getLeft methods obtain the absolute position of the text box, relative to the upper left corner of the browser.
The background java code is as follows:
public void findDept() throws IOException{ String partDeptName = this.request.getParameter("names"); partDeptName = java.net.URLDecoder.decode(partDeptName, "UTF-8"); Map<String,String> userMap = DataAccessDriver.getInstance().newUserDAO().getDeptByPart("%" + partDeptName + "%"); this.response.setContentType("text/xml;charset=UTF-8"); this.response.setHeader("Cache-Control", "no-cache"); ServletOutputStream pw = this.response.getOutputStream(); OutputStreamWriter out = new OutputStreamWriter(pw,"UTF-8"); out.write("<res>"); Iterator<Map.Entry<String, String>> it = userMap.entrySet().iterator(); while(it.hasNext()){ Map.Entry<String, String> entry=(Map.Entry<String,String>)it.next(); out.write("<id>"+entry.getKey()+"</id>"); out.write("<dept>"+entry.getValue()+"</dept>"); } out.write("</res>"); out.flush(); out.close(); }
Key points:
1, pay attention to decoding the parameters.
2, perform fuzzy matching according to the situation when querying.
3. The returned data is in xml mode, or in json mode.
4, the return method is used here
ServletOutputStream pw = this.response.getOutputStream(); OutputStreamWriter out = new OutputStreamWriter(pw,"UTF-8");
Such a flow is limited by the system framework. If you use a simple servlet, you can use PrintWriter out = response.getWriter(); of course the out method It is println(), which can also be changed flexibly according to the situation of your own framework.
For more articles related to ajax java realizing the automatic completion function, please pay attention to the PHP Chinese website!

This article analyzes the top four JavaScript frameworks (React, Angular, Vue, Svelte) in 2025, comparing their performance, scalability, and future prospects. While all remain dominant due to strong communities and ecosystems, their relative popul

This article addresses the CVE-2022-1471 vulnerability in SnakeYAML, a critical flaw allowing remote code execution. It details how upgrading Spring Boot applications to SnakeYAML 1.33 or later mitigates this risk, emphasizing that dependency updat

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

Node.js 20 significantly enhances performance via V8 engine improvements, notably faster garbage collection and I/O. New features include better WebAssembly support and refined debugging tools, boosting developer productivity and application speed.

Iceberg, an open table format for large analytical datasets, improves data lake performance and scalability. It addresses limitations of Parquet/ORC through internal metadata management, enabling efficient schema evolution, time travel, concurrent w

This article explores methods for sharing data between Cucumber steps, comparing scenario context, global variables, argument passing, and data structures. It emphasizes best practices for maintainability, including concise context use, descriptive

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability


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

Zend Studio 13.0.1
Powerful PHP integrated development environment

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

Atom editor mac version download
The most popular open source editor

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
