Ajax動態更新頁面

來源:互聯網
上載者:User
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" style="display:none;">
  <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基礎教程  作筆記吧 




相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.