Ajax动态更新页面

80酷酷网    80kuku.com

  ajax|动态|页面  业务逻辑:动态添加员工信息至列表,列表动态删除员工信息

    页面:employeeList.jsp

<html>
<head>
<title>员工列表</title>

<script type="text/javascript">
var xmlHttp;
var name;
var title;
var department;
var deleteID;
var EMP_PREFIX = "emp-";

//创建XMLHttpRequest对象
function createXMLHttpRequest() {
    if (window.ActiveXObject) {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    }
}

//增加员工   
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);
}

//构造参数字串
function createAddQueryString(name, title, department, action) {
    var queryString = "name=" + name
        + "&title=" + title
        + "&department=" + department
        + "&action=" + action;
    return queryString;
}

//回调方法   
function handleAddStateChange() {
    if(xmlHttp.readyState == 4) {
        if(xmlHttp.status == 200) {
            updateEmployeeList();
            clearInputBoxes();
        }
        else {
            alert("Error while adding employee.");
        }
    }
}

//清空输入框
function clearInputBoxes() {
    document.getElementById("name").value = "";
    document.getElementById("title").value = "";
    document.getElementById("dept").value = "";
}

//删除员工
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);
}

//更新员工列表
function updateEmployeeList() {
    var responseXML = xmlHttp.responseXML;

    var status = responseXML.getElementsByTagName("status").item(0).firstChild.nodeValue;
    status = parseInt(status);
    if(status != 1) {
        return;
    }

    //创建行
    var row = document.createElement("tr");
    var uniqueID = responseXML.getElementsByTagName("uniqueID")[0].firstChild.nodeValue;
    row.setAttribute("id", EMP_PREFIX + uniqueID);
   
    //创建列
    row.appendChild(createCellWithText(name));
    row.appendChild(createCellWithText(title));
    row.appendChild(createCellWithText(department));
   
    //删除按钮
    var deleteButton = document.createElement("input");
    deleteButton.setAttribute("type", "button");
    deleteButton.setAttribute("value", "删除");
    deleteButton.onclick = function () { deleteEmployee(uniqueID); };
    cell = document.createElement("td");
    cell.appendChild(deleteButton);
    row.appendChild(cell);
   
    document.getElementById("employeeList").appendChild(row);
    updateEmployeeListVisibility();
}

//创建列
function createCellWithText(text) {
    var cell = document.createElement("td");
    cell.appendChild(document.createTextNode(text));
    return cell;
}

//删除行的回调方法
function handleDeleteStateChange() {
    if(xmlHttp.readyState == 4) {
        if(xmlHttp.status == 200) {
            deleteEmployeeFromList();
        }
        else {
            alert("Error while deleting employee.");
        }
    }

}

//删除行
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);
   
    //更新列表可视效果
    updateEmployeeListVisibility();
}

//更新列表可视效果
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>
</head>

<body>
  <h1>员工列表</h1>
 
  <form action="#">
    <table width="80%" border="0">
        <tr>
            <td>姓名: <input type="text" id="name"/></td>
            <td>职务: <input type="text" id="title"/></td>
            <td>部门: <input type="text" id="dept"/></td>
        </tr>
        <tr>
            <td colspan="3" align="center">
                <input type="button" value="增加" />
            </td>
        </tr>
    </table>
  </form>

  <span id="employeeListSpan" <h2>Employees:</h2>
 
  <table border="1" width="80%">
    <tbody id="employeeList"></tbody>
  </table>
  </span>
</body>
</html>

服务器: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 {
    //处理方法参数
    String action = request.getParameter("action");
    if (action.equals("add")){
      addEmployee(request,response);
    }else if (action.equals("delete")){
      deleteEmployee(request,response);
    }
  }

  //增加员工
  protected void addEmployee(HttpServletRequest request,
                             HttpServletResponse response) throws
      ServletException, IOException {
    //得到主键id
    String uniqueID = storeEmployee();

    //创建响应字串
    StringBuffer xml = new StringBuffer("<result><uniqueID>");
    xml.append(uniqueID);
    xml.append("</uniqueID>");
    xml.append("<status>1</status>");
    xml.append("</result>");

    //发送
    sendResponse(response, xml.toString());
  }

  //删除员工
  protected void deleteEmployee(HttpServletRequest request,
                             HttpServletResponse response) throws
      ServletException, IOException {
    //得到参数id
    String id = request.getParameter("id");
   
    //创建响应字串
    StringBuffer xml = new StringBuffer("<result>>");
    xml.append("<status>1</status>");
    xml.append("</result>");

    //发送
    sendResponse(response, xml.toString());
  }

  //发送响应字串
  private void sendResponse(HttpServletResponse response, String responseText)throws IOException {
    response.setContentType("text/xml");
    response.getWriter().write(responseText);
  }

  //模拟数据库,得到主键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;
  }
}

参考:Ajax基础教程  作笔记吧 




分享到
  • 微信分享
  • 新浪微博
  • QQ好友
  • QQ空间
点击: