Ajax+java implements automatic completion function method
[Related article recommendations: ajax video tutorial]
Baidu suggestions have given us great convenience, just like when we talk to people Sometimes, when you nod and he knows the end, there is no need to waste words, so that we can spend a long time with him, relaxed and happy.
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 in 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:
The code is as follows:
var xmlHttpRequest; var table; var tbody; var p; 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){ p.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"); p = document.getElementById("p"); tbody = document.getElementById("tbody"); p.style.width = input.offsetWidth-2; p.style.border = "gray 1px solid"; p.style.left = getLeft(input); p.style.top = getTop(input)+input.offsetHeight+6; curIndex = -1; input.focus();//p.style.left+","+p.style.top } function clearNames(){ var ind = tbody.childNodes.length; for(i=ind-1;i>=0;i--){ tbody.removeChild(tbody.childNodes[i]); } p.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(p.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 for 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, getTop and getLeft methods are to obtain the absolute position of the text box, relative to the upper left corner of the browser.
The background java code is as follows:
The 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 format, or in json format.
4, the return method is used here
The code is as follows:
ServletOutputStream pw = this.response.getOutputStream(); OutputStreamWriter out = new OutputStreamWriter(pw,"UTF-8");
Such a flow is limited by the framework of this system. If you use a simple servlet, you can use PrintWriter out = response.getWriter(); Of course, the out method is println(), which can also be changed flexibly according to the situation of your own framework.
Related learning recommendations: java basic tutorial
The above is the detailed content of Ajax+java implements automatic completion function method. For more information, please follow other related articles on the PHP Chinese website!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


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

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

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

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),

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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor