Ajax:动态更新Web页面

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript">
        var xmlHttp;
        var name;
        var title;
        var department;
        var deleteID;
        var EMP_PREFIX = "emp_";

        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 = "WS.asmx/EmployeeList?" + createAddQueryString(name, title, department, "add") + "&ts=" + new Date().getTime();
            createXMLHttpRequest();
            xmlHttp.onreadystatechange = handleStateChange;
            xmlHttp.open("GET", url, true);
            xmlHttp.send(null)
        }
        function createAddQueryString(name, title, department, action) {
            var queryString = "name=" + name + "&title=" + title + "&department=" + department + "&a=" + action;
            return queryString;
        }
        function handleStateChange() {
            if (xmlHttp.readyState == 4) {
                if (xmlHttp.status == 200) {
                    updateEmployeeList();
                    clearInputBoxs();
                }
                else {
                    alert("Error while adding employe");
                }
            }
        }
        function clearInputBoxs() {
            document.getElementById("name").value = "";
            document.getElementById("title").value = "";
            document.getElementById("dept").value = "";
        }

        function deleteEmployee(id) {
            deleteID = id;

            var url = "WS.asmx/EmployeeList?" + "a=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;
            alert(status);
            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", "Delete");

            deleteButton.onclick = function () { deleteEmployee(uniqueID); };
            cell = document.createElement("td");
            cell.appendChild(deleteButton);
            row.appendChild(cell);
            document.getElementById("employeeList").appendChild(row);
            updateEmployeeListVisiblity();
        }

        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 adding employe");
                }
            }
        }
        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);
            updateEmployeeListVisiblity();
        }

        function updateEmployeeListVisiblity() {
            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>
        Employee List</h1>
    <form action="#">
    <table width="80%" border="0">
        <tr>
            <td>
                Name:<input type="text" id="name" />
            </td>
            <td>
                Title:<input type="text" id="title" />
            </td>
            <td>
                Department:<input type="text" id="dept" />
            </td>
        </tr>
        <tr>
            <td colspan="3" align="center">
                <input type="button" value="Add" onclick="addEmployee();" />
            </td>
        </tr>
    </table>
    </form>
    <span id="employeeListSpan" style="display: none">
        <h2>
            Employee:</h2>
        <table border="1" width="80%">
            <tbody id="employeeList">
            </tbody>
        </table>
    </span>
</body>
</html>

后台代码如下:

 [WebMethod]
        public void EmployeeList()
        {
            string action = Context.Request.QueryString["a"];
            if (action.Equals("add"))
            {
                addEmployee(Context.Request, Context.Response);
            }
            else if (action.Equals("delete"))
            {
                deleteEmployee(Context.Request, Context.Response);
            }

        }

        private void deleteEmployee(HttpRequest httpRequest, HttpResponse httpResponse)
        {
            string id = httpRequest.QueryString["id"];
            StringBuilder xml = new StringBuilder("<result>");
            xml.Append("<status>1</status>");
            xml.Append("</result>");
            sendResponse(httpResponse, xml.ToString());
        }

        private void addEmployee(HttpRequest httpRequest, HttpResponse httpResponse)
        {
            string uniqueID = storeEmployee();
            StringBuilder xml = new StringBuilder("<result><uniqueID>");
            xml.Append(uniqueID);
            xml.Append("</uniqueID>");
            xml.Append("<status>1</status>");//书中没有这行代码,请注意
            xml.Append("</result>");
            sendResponse(httpResponse, xml.ToString());
        }
        private void addEmployee()
        {

        }
        private void sendResponse(HttpResponse httpResponse, string responseText)
        {
            httpResponse.ContentType = "text/xml";
            httpResponse.Write(responseText);

        }

        private string storeEmployee()
        {
            string uniqueID = "";
            Random r = new Random();
            for (int i = 0; i < 8; i++)
            {
                uniqueID += r.Next(9);
            }
            return uniqueID;
        }

运行效果如下:

点击删除按钮后:

posted on 2012-10-10 09:58  lufangtao  阅读(1758)  评论(0编辑  收藏  举报

导航