Ajax Java Implementation _javascript skill of automatic completion function

Source: Internet
Author: User
Baidu proposed to give us great convenience, just as we talk to people, you nod him to know the end, do not have to spend too much breath, so we get along with it for a long time relaxed pleasure.

All know Baidu is recommended to do with Ajax, want to do a fast and stable, can be replicated can be transplanted is not easy. Search on the internet for a long time, many are ASP or PHP, and the use of jquery, but there are too few descriptive documents, spend a few hours of research than to write their own. According to a PDF document provided by the information, with a small half a day, finally realized. Share with you here.
The principle flow chart is as follows:

The flowchart is clear, there is nothing to say, the following post code.
JavaScript code:
Copy Code code as follows:

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 ();
}
}
Send Request
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 ("The page you requested has an exception!") ");
}
}
}
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 = "Close";
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;
}
}
}
}
Get the ordinate of an element
function GetTop (e) {
var offset=e.offsettop;
if (e.offsetparent!=null) offset+=gettop (e.offsetparent);
return offset;
}
Get the horizontal axis of an element
function GetLeft (e) {
var offset=e.offsetleft;
if (e.offsetparent!=null) offset+=getleft (e.offsetparent);
return offset;
}

The code is too much, a bit messy, not using jquery, but more can show the author's foundation. The following points are elaborated:
1,setposition () is used to initialize the overall needs of the variables, so the page should be loaded in the first call, such as in the body of the OnLoad method, or other ways can be.
2,findnames () is the way to operate Ajax, familiar with Ajax people can see that the most important thing is to the parameters of the two-time Code encodeURI (), the corresponding in the background to decode.
3,processmatchresponse () is a callback function that handles the data returned from the background, and is referred to setnames () for processing.
4,setnames Displays the contents of the hint in table format. Here more is the knowledge of JS and node.
The 5,gettop and GetLeft methods are to get the absolute position of the text box, relative to the upper-left corner of the browser.
The background Java code is as follows:
Copy Code code 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 ();

}

Main points
1, note the decoding of the parameters.
2, the query is based on the situation of fuzzy matching.
3, the return data is either XML-or JSON-based.
4, the way back is used here
Copy Code code as follows:

Servletoutputstream pw = This.response.getOutputStream ();
OutputStreamWriter out = new OutputStreamWriter (PW, "UTF-8");

Such a stream is limited by the framework of this system, if the use of a simple servlet, you can use printwriter out = Response.getwriter (), of course out of the method is println (), can also be flexible according to the circumstances of their own framework changes.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.