[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!