Ajax Dynamic Update page

Source: Internet
Author: User
Tags add date key return string tostring window stringbuffer
ajax| Dynamic | Page business logic: Dynamically add employee information to list, list delete employee information dynamically

Page: employeelist.jsp

<title> Employee List </title>

<script type= "Text/javascript" >
var xmlHttp;
var name;
var title;
VAR department;
var Deleteid;
var emp_prefix = "emp-";

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

//Increase employee    
Function AddEmployee () {
    name = document.getElementById ("name" ). Value;
    title = document.getElementById ("title"). Value;
    Department = document.getElementById ("dept"). Value;
    action = "Add";

    if (name = = "" | | title = = "" | | Department = = "") {
        return;
   }
   
    var url = "Employeelistservlet?"
        + createaddquerystring (name, title, department, "add")
         + "&ts=" + New Date (). GetTime ();
       
    createxmlhttprequest ();
    xmlhttp.onreadystatechange = Handleaddstatechange;
    Xmlhttp.open ("Get", url, True);
    xmlhttp.send (null);
}

//constructor parameter string
function createaddquerystring (name, title, Department, Action) {
    var querystring = "Name=" + name
        + "&title=" + title
         + "&department=" + Department
        + "&action=" + Action
    return querystring;
}

callback method
function Handleaddstatechange () {
if (xmlhttp.readystate = = 4) {
if (Xmlhttp.status = = 200) {
Updateemployeelist ();
Clearinputboxes ();
}
else {
Alert ("Error while adding employee.");
}
}
}

Empty the input box
function Clearinputboxes () {
document.getElementById ("name"). Value = "";
document.getElementById ("title"). Value = "";
document.getElementById ("dept"). Value = "";
}

Delete Employee
function Deleteemployee (ID) {
Deleteid = ID;

var url = "Employeelistservlet?"
+ "Action=delete"
+ "&id=" + ID
+ "&ts=" + New Date (). GetTime ();

Createxmlhttprequest ();
Xmlhttp.onreadystatechange = Handledeletestatechange;
Xmlhttp.open ("Get", url, True);
Xmlhttp.send (NULL);
}

Update Employee List
function Updateemployeelist () {
var responsexml = Xmlhttp.responsexml;

var status = Responsexml.getelementsbytagname ("status"). Item (0). Firstchild.nodevalue;
Status = parseint (status);
if (status!= 1) {
Return
}

Create a row
var row = document.createelement ("tr");
var UniqueID = responsexml.getelementsbytagname ("UniqueID") [0].firstchild.nodevalue;
Row.setattribute ("id", Emp_prefix + UniqueID);

Creating columns
Row.appendchild (Createcellwithtext (name));
Row.appendchild (Createcellwithtext (title));
Row.appendchild (Createcellwithtext (department));

Delete button
var DeleteButton = document.createelement ("input");
Deletebutton.setattribute ("Type", "button");
Deletebutton.setattribute ("Value", "delete");
Deletebutton.onclick = function () {deleteemployee (UniqueID);};
Cell = document.createelement ("TD");
Cell.appendchild (DeleteButton);
Row.appendchild (cell);

document.getElementById ("EmployeeList"). appendchild (row);
Updateemployeelistvisibility ();
}

Creating columns
function Createcellwithtext (text) {
var cell = document.createelement ("TD");
Cell.appendchild (document.createTextNode (text));
return cell;
}

callback method for deleting rows
function Handledeletestatechange () {
if (xmlhttp.readystate = = 4) {
if (Xmlhttp.status = = 200) {
Deleteemployeefromlist ();
}
else {
Alert ("Error while deleting employee.");
}
}

}

//Delete Row
Function deleteemployeefromlist () {
    var status = XmlHttp.responseXML.getElementsByTagName ("status"). Item (0). Firstchild.nodevalue;
    status = parseint (status);
    if (status!= 1) {
        return;
   }
   
    var rowtodelete = document.getElementById (emp_ PREFIX + Deleteid);
    var employeelist = document.getElementById ("EmployeeList");
    Employeelist.removechild (rowtodelete);
   
   //Update list visual effects
    updateemployeelistvisibility ();
}

Update list Visual effects
function updateemployeelistvisibility () {
var employeelist = document.getElementById ("EmployeeList");
if (EmployeeList.childNodes.length > 0) {
document.getElementById ("Employeelistspan"). Style.display = "";
}
else {
document.getElementById ("Employeelistspan"). Style.display = "None";
}
}
</script>

<body>

<form action= "#" >
<table width= "80%" border= "0" >
<tr>
<td> Name: <input type= "text" id= "name"/></td>
<td> Position: <input type= "text" id= "title"/></td>
<td> Department: <input type= "text" id= "dept"/></td>
</tr>
<tr>
&LT;TD colspan= "3" align= "Center" >
<input type= "button" value= "Add"/>
</td>
</tr>
</table>
</form>

<span id= "Employeelistspan" style= "Display:none;" >

<table border= "1" width= "80%" >
<tbody id= "EmployeeList" ></tbody>
</table>
</span>
</body>

Server: Employeelistservlet.java

Package AJAXBOOK.CHAP4;

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

public class Employeelistservlet
Extends HttpServlet {
private static final String Content_Type = "text/html;" CHARSET=GBK ";

Initialize Global Variables
public void Init () throws Servletexception {
}

Process the HTTP GET request
public void doget (HttpServletRequest request, httpservletresponse response) throws
Servletexception, IOException {
Processing method parameters
String action = request.getparameter ("action");
if (Action.equals ("add")) {
AddEmployee (Request,response);
}else if (action.equals ("delete")) {
Deleteemployee (Request,response);
}
}

Increase staff
protected void AddEmployee (HttpServletRequest request,
HttpServletResponse response) throws
Servletexception, IOException {
Get primary Key ID
String UniqueID = Storeemployee ();

Create a response string
StringBuffer XML = new StringBuffer ("<result><uniqueID>");
Xml.append (UniqueID);
Xml.append ("</uniqueID>");
Xml.append ("<status>1</status>");
Xml.append ("</result>");

Send
Sendresponse (response, xml.tostring ());
}

Delete Employee
protected void Deleteemployee (HttpServletRequest request,
HttpServletResponse response) throws
Servletexception, IOException {
Get parameter ID
String id = request.getparameter ("id");

Create a response string
StringBuffer XML = new StringBuffer ("<result>>");
Xml.append ("<status>1</status>");
Xml.append ("</result>");

Send
Sendresponse (response, xml.tostring ());
}

Send Response string
private void Sendresponse (httpservletresponse response, String responsetext) throws IOException {
Response.setcontenttype ("Text/xml");
Response.getwriter (). write (ResponseText);
}

Simulate database, get primary key ID
Private String Storeemployee () {
String UniqueID = "";
Random randomizer = new Random (System.currenttimemillis ());
for (int i = 0; i < 8; i++) {
UniqueID + + randomizer.nextint (9);
}

return UniqueID;
}
}

Reference: Ajax Basics Tutorial Take notes.




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.