Ajax implementation is done automatically

Source: Internet
Author: User
Tags add end return string window
Ajax business logic: text box implementation automatically completes the introduction of Prototype.js package

Page: autocomplete.jsp

<%@ page contenttype= "text/html; CHARSET=GBK "%>
<title>
Ajax Automatic Completion
</title>
<!--definition style-->
<style type= "Text/css" >
. mouseout{
Background: #708090;
Color: #FFFAFA;
}

. mouseover{
Background: #FFFAFA;
Color: #000000;
}
</style>
<script src= "Prototype.js" ></script>
<script type= "Text/javascript" >
var xmlHttp;
var Completediv;
var Inputfield;
var nametable;
var nametablebody;

       //Create XMLHttpRequest Objects
         function Createxmlhttprequest () {
            if ( Window. ActiveXObject) {
                XmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");
           }
            else if (window. XMLHttpRequest) {
                XmlHttp = new XMLHttpRequest ();
           }
       }

Initializing variables
function Initvars () {
Inputfield = $ ("names");
NameTable = $ ("name_table");
Completediv = $ ("popup");
Nametablebody = $ ("Name_table_body");
}

Execution method
function Findnames () {
Initvars ();
If you have an input value
if (InputField.value.length > 0) {
Createxmlhttprequest ();
var url = "autocompleteservlet?names=" + Escape (inputfield.value);
Xmlhttp.open ("Get", url,true);
Xmlhttp.onreadystatechange = callback;
Xmlhttp.send (NULL);
}
}

       //Callback methods
        function Callback () {
         if (xmlhttp.readystate = 4) {
                 if (xmlhttp.status = =) {
                     var name = XmlHttp.responseXML.getElementsByTagName ("name") [0].firstchild.data;
                     Setnames (XmlHttp.responseXML.getElementsByTagName ("name"));
               }
           }
       }

       //populating forms
        function Setnames (the_names) {
         clearnames ();
                var size = the_ Names.length;
               //set coordinates
                 setoffsets ();

                var row,cel, Txtnode;
                for (var i = 0; i < Size i++) {
                 var NextNode = The_names[i].firstchild.data;
                         row = document.createelement ("tr");
                         cell = document.createelement ("TD");

                         cell.onmouseout = function () {this.classname= "mouseout";};
                         cell.onmouseover = function () {this.classname= "MouseOver";};
                         Cell.setattribute ("bgcolor", "#FFFAFA");
                         Cell.setattribute ("border", "0");
                         Cell.onclick = function () {populatename (this);};

                         Txtnode = document.createTextNode (NextNode);
                         Cell.appendchild (Txtnode);
                         row.appendchild (cell);
                         nametablebody.appendchild (row);
               }
       }

       //Set coordinates
        function setoffsets ( {
         var end = Inputfield.offsetwidth;
                var left = Calculateoffsetleft (Inputfield);
                var top = Calculateoffsettop (Inputfield) + inputfield.offsetheight;

CompleteDiv.style.border = "Black 1px solid";
CompleteDiv.style.left = left + "px";
CompleteDiv.style.top = top + "px";
NameTable.style.width = end + "px";
}

Calculate left coordinate point
function Calculateoffsetleft (field) {
Return Calculateoffset (field, "offsetleft");
}

Calculate Top coordinate points
function calculateoffsettop (field) {
Return Calculateoffset (field, "offsettop");
}

To compute a coordinate point
function Calculateoffset (field,attr) {
var offset = 0;
while (field) {
Offset + + field[attr];
field = Field.offsetparent;
}

return offset;
}

Automatic completion
function Pupulatename (cell) {
Inputfield.value = Cell.firstChild.nodeValue;
Clearnames ();
}

Clear
function Clearnames () {
var ind = NameTableBody.childNodes.length;
for (var i = ind-1 i >= 0; i--) {
Nametablebody.removechild (Nametablebody.childnode[i]);
}
CompleteDiv.style.border = "None";
}
</script>
<body>
Ajax Automatic Completion sample
Name:
<input type= "text" size= "id=" names "onkeyup=" Findnames (); "style=" HEIGHT:20; " />
<div style= "Position:absolute" id= "Popup" >
<table id= "name_table" bgcolor= "#FFFAFA" border= "0" cellpadding= "0" cellspacing= "0" >
<tbody id= "Name_table_body" >
</tbody>
</table>
</div>
</body>

Server side: Autocompleteservlet

Package AJAXBOOK.CHAP4;

Import javax.servlet.*;
Import javax.servlet.http.*;
Import java.io.*;
Import java.util.*;

public class Autocompleteservlet
Extends HttpServlet {
private static final String Content_Type = "text/html;" CHARSET=GBK ";
Private List names = new ArrayList ();

Initializing a Collection
public void Init () throws Servletexception {
Names.add ("Abe");
Names.add ("Abel");
Names.add ("Abigail");
Names.add ("Abner");
Names.add ("Abraham");
Names.add ("Marcus");
Names.add ("Marge");
Names.add ("Marie");
}

Handling Get methods
public void doget (HttpServletRequest request, httpservletresponse response) throws
Servletexception, IOException {
Get the value of the parameter
String prefix = request.getparameter ("names");
Find a list that matches the criteria
Nameservice service = nameservice.getinstance (names);
List matching = service.findnames (prefix);

If the list has a value
if (matching.size () > 0) {
PrintWriter out = Response.getwriter ();
Constructing an XML string
Response.setcontenttype ("Text/xml");
Response.setheader ("Cache-control", "No-cache");

Out.println ("<response>");
Iterator iter = Matching.iterator ();
while (Iter.hasnext ()) {
String name = (string) iter.next ();
Out.println ("<name>" + name + "</name>");
}
Out.println ("</response>");

matching = null;
Service = NULL;
Out.close ();
}else{
Response.setstatus (httpservletresponse.sc_no_content);
}
}

Clean up resources
public void Destroy () {
}
}

Processing class: Nameservice

Package AJAXBOOK.CHAP4;

Import java.util.List;
Import java.util.ArrayList;
Import Java.util.Iterator;

public class Nameservice {
private List names;

/**
* Default constructor
* @param list_of_name List
*/
Private Nameservice (List list_of_name) {
This.names = List_of_name;
}

/**
* Return Instance
* @param list_of_name List
* @return Nameservice
*/
public static Nameservice getinstance (List list_of_name) {
return new Nameservice (List_of_name);
}

/**
* Find a list that meets the criteria
* @param prefix String prefix
* @return List
*/
Public List findnames (String prefix) {
String prefix_upper = Prefix.touppercase ();
List matches = new ArrayList ();
Iterator iter = Names.iterator ();
while (Iter.hasnext ()) {
String name = (string) iter.next ();
String name_upper_case = Name.touppercase ();
if (Name_upper_case.startswith (Prefix_upper)) {
Boolean result = Matches.add (name);
}
}

return matches;
}
}



Related Article

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.