ホームページ  >  記事  >  Java  >  ajax Javaはオートコンプリート機能を実装します

ajax Javaはオートコンプリート機能を実装します

高洛峰
高洛峰オリジナル
2017-01-12 09:24:571346ブラウズ

Baidu が ajax の使用を推奨していることは誰もが知っていますが、これを高速、安定、複製可能、移植可能にするのは簡単ではありません。長い間ネットで検索すると、多くはaspやphpであり、jqueryを使用するものもありますが、説明ドキュメントが少なすぎます。調べるのに時間を費やすよりも自分で書いた方が良いです。 PDFドキュメントで提供される情報を基に、最終的にそれを達成するまでに半日かかりました。ここでみんなと共有してください。
原則的なフローチャートは次のとおりです:

ajax java 实现自动完成功能

フローチャートは非常に明確であり、言うことは何もありません。コードは次のとおりです。
Javascript コード:

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 = &#39;mouseOut&#39;; 
} 
row.onmouseover = function(){ 
clearSelected(); 
this.className = &#39;mouseOver&#39;; 
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=&#39;mouseOut&#39;; 
curIndex = curIndex-1; 
if(curIndex>=0){ 
table.rows[curIndex].className = &#39;mouseOver&#39;; 
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 = &#39;mouseOut&#39;; 
} 
curIndex = curIndex+1; 
table.rows[curIndex].className = &#39;mouseOver&#39;; 
input.value = table.rows[curIndex].cells[0].innerText; 
r_userId.value = table.rows[curIndex].cells[1].innerText; 
}else{ 
table.rows[curIndex].className = &#39;mouseOut&#39;; 
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; 
}

コードが多すぎて少し面倒ですが、jquery は使用しませんが、作者のスキルがよくわかります。以下の点について説明します:
1. setPosition() は、グローバルに必要なさまざまな変数を初期化するために使用されるため、本文の onload メソッドやその他のメソッドなど、ページが読み込まれるときに最初に呼び出される必要があります。
2. findNames() は、ajax を操作するメソッドです。ajax に精通している人なら、最も重要なことはパラメータ encodeURI() を再エンコードし、それに応じてバックグラウンドでデコードすることであることが理解できます。
3. processMatchResponse() は、バックグラウンドから返されたデータを処理するために使用されるコールバック関数です。これは setNames() によって処理されます。
4. SetNames はテーブル モードを使用してプロンプトの内容を表示します。 JS とノードに関する詳細な知識は次のとおりです。
5. getTop メソッドと getLeft メソッドは、ブラウザの左上隅を基準としたテキスト ボックスの絶対位置を取得します。
バックグラウンドの Java コードは次のとおりです:

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(); 

}

重要なポイント:
1. パラメーターのデコードに注意してください。
2. クエリ時に状況に応じてファジーマッチングが行われます。
3. 返されるデータは xml 形式または json 形式です。
4. return メソッドはこちら

ServletOutputStream pw = this.response.getOutputStream(); 
OutputStreamWriter out = new OutputStreamWriter(pw,"UTF-8");

このようなフローは、単純なサーブレットを使用する場合は、 もちろん、out メソッドは println() を使用できます。 、独自のフレームワークの状況に応じて柔軟に変更することもできます。

オートコンプリート機能を実装する ajax java に関連するその他の記事については、PHP 中国語 Web サイトに注目してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。