• Ajax:发送请求与处理响应


    1.处理服务器响应

     XMLHttpRequest对象提供了两个可以用来访问服务器响应的属性。第一个属性responseText将响应提供了一个串,第二个属性responseXML将响应提供了一个XML对象。

      1.1 利用innerHTML属性创建动态内容

      innerHTML.xml 文件内容如下:

    <?xml version="1.0" encoding="utf-8" ?>
    <table border="1">
      <tbody>
        <tr>
          <th>姓名</th>
          <th>性别</th>
          <th>年龄</th>
        </tr>
        <tr>
          <td>小明</td>
          <td></td>
          <td>12</td>
        </tr>
        <tr>
          <td>小红</td>
          <td></td>
          <td>13</td>
        </tr>
        <tr>
          <td>小强</td>
          <td></td>
          <td>13</td>
        </tr>
      </tbody>
    </table>

    innerHTML.htm文件内容如下:

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
        <script type="text/javascript">
            var xmlHttp;
            function createXMLHttpRequest() {
                if (window.ActiveXObject) {
                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTp");
                }
                else if (window.XMLHttpRequest) {
                    xmlHttp = new XMLHttpRequest();
                }
            }
            function startRequest() {
                createXMLHttpRequest();
                xmlHttp.onreadystatechange = handleStateChange;
                xmlHttp.open("GET", "innerHTML.xml", true);
                xmlHttp.send(null);
    
            }
            function handleStateChange() {
                if (xmlHttp.readyState == 4) {
                    if (xmlHttp.status == 200) {
                        document.getElementById("results").innerHTML = xmlHttp.responseText;
                    }
                }
            }
        </script>
    </head>
    <body>
        <form action="#">
        <input type="button" value="加载" onclick="startRequest();" />
        <div id="results">
        </div>
        </form>
    </body>
    </html>

    运行效果如下:

    点击按钮后:

    1.2 将响应解析为XML

     City.xml文件内容如下:

    <?xml version="1.0" encoding="utf-8" ?>
    <>
      <山东>
        <>
          济南
        </>
        <>
          青岛
        </>
      </山东>
      <北京>
        <>
          北京市
        </>
      </北京>
    </>

    City.HTML文件内容如下:

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
        <script type="text/javascript">
            var xmlHttp;
            var requestType = "";
            function createXMLHttpRequest() {
                if (window.ActiveXObject) {
                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTp");
                }
                else if (window.XMLHttpRequest) {
                    xmlHttp = new XMLHttpRequest();
                }
            }
            function startRequest(requestedList) {
                requestType = requestedList;
                createXMLHttpRequest();
                xmlHttp.onreadystatechange = handleStateChange;
                xmlHttp.open("GET", "City.xml", true);
                xmlHttp.send(null);
    
            }
            function handleStateChange() {
                if (xmlHttp.readyState == 4) {
                    if (xmlHttp.status == 200) {
                        if (requestType == "山东") {
                            listShangDong();
                        }
                        else if (requestType == "所有") {
                            listAllCity();
                        }
                    }
                }
            }
            function listShangDong() {
                var xmlDoc = xmlHttp.responseXML;
                var node = xmlDoc.getElementsByTagName("山东")[0];
                var out = "山东省";
                var city = node.getElementsByTagName("");
                outputList("山东省", city);
            }
    
            function listAllCity() {
                var xmlDoc = xmlHttp.responseXML;
                var city = xmlDoc.getElementsByTagName("");
                outputList("所有市", city);
            }
    
            function outputList(title, states) {
                var out = title;
                var currentState = null;
                for (var i = 0; i < states.length; i++) {
                    currentState = states[i];
                    out = out + "\n-" + currentState.childNodes[0].nodeValue;
                }
                alert(out);
            }
        </script>
    </head>
    <body>
        <form>
        <input type="button" value="山东省" onclick="startRequest('山东');" />
        <input type="button" value="所有市" onclick="startRequest('所有');" />
        </form>
    </body>
    </html>

    运行效果如下:

    1.3 动态编辑网页

    Book.XML文件内容如下:

    <?xml version="1.0" encoding="utf-8" ?>
    <书架>
      <>
        <书名>
          Ajax基础教程
        </书名>
        <出版社>
          人民邮电出版社
        </出版社>
        <价格>
          35.00
        </价格>
      </>
      <>
        <书名>
          Programming ASP.NET(中文版)
        </书名>
        <出版社>
          电子工业出版社
        </出版社>
        <价格>
          99.00
        </价格>
      </>
    </书架>

    Book.htm文件如下:

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
        <script type="text/javascript">
            var xmlHttp;
            function createXMLHttpRequest() {
                if (window.ActiveXObject) {
                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTp");
                }
                else if (window.XMLHttpRequest) {
                    xmlHttp = new XMLHttpRequest();
                }
            }
            function startRequest() {
    
                createXMLHttpRequest();
                xmlHttp.onreadystatechange = handleStateChange;
                xmlHttp.open("GET", "Book.xml", true);
                xmlHttp.send(null);
    
            }
            function handleStateChange() {
                if (xmlHttp.readyState == 4) {
                    if (xmlHttp.status == 200) {
                        clearPreviousResults();
                        parseResults();
                    }
                }
            }
    
            function clearPreviousResults() {
                var header = document.getElementById("header");
                if (header.hasChildNodes()) {
                    header.removeChild(header.childNodes[0]);
                }
                var tableBody = document.getElementById("resultsBody");
                while (tableBody.childNodes.length > 0) {
                    tableBody.removeChild(tableBody.childNodes[0]);
                }
            }
            function parseResults() {
                var results = xmlHttp.responseXML;
    
                var book = null;
                var name = "";
                var press = "";
                var price = "";
    
                var books = results.getElementsByTagName("");
    
                for (var i = 0; i < books.length; i++) {
                    book = books[i];
    
                    name = book.getElementsByTagName("书名")[0].firstChild.nodeValue;
                    press = book.getElementsByTagName("出版社")[0].firstChild.nodeValue;
                    price = book.getElementsByTagName("价格")[0].firstChild.nodeValue;
                    addTableRow(name, press, price);
                }
                var header = document.createElement("h2");
                var headerText = document.createTextNode("Results:");
                header.appendChild(headerText);
                document.getElementById("header").appendChild(header);
    
                document.getElementById("resultsTable").setAttribute("border", "2");
            }
    
            function addTableRow(name, press, price) {
                var row = document.createElement("tr");
                var cell = createCellWithText(name);
                row.appendChild(cell);
    
                cell = createCellWithText(press);
                row.appendChild(cell);
    
                cell = createCellWithText(price);
                row.appendChild(cell);
                document.getElementById("resultsBody").appendChild(row);
            }
    
            function createCellWithText(text) {
                var cell = document.createElement("td");
                var textNode = document.createTextNode(text);
                cell.appendChild(textNode);
                return cell;
            }
        </script>
    </head>
    <body>
        <form action="#">
        <input type="button" value="搜索" onclick="startRequest();" />
        </form>
        <span id="header"></span>
        <table id="resultsTable" width="75%" border="0'">
            <tbody id="resultsBody">
            </tbody>
        </table>
    </body>
    </html>

    运行效果如下:

    2. 发送参数

    GET方法把值作为名/值对放在请求URL中传递。资源URL的最后有一个问号(?),问号后面是名/值对。名/值对采用name=value的形式,各个名/值对之间用于号(&)分隔。

    POST方法向服务器发送命令参数时,与采用GET方法几乎是一样的。类似于GET方法,POST方法会把参数编码为名/值对,形式为name=value,每个名/值对之间也用与号(&)分隔。这两种方法的主要区别在于,POST方法将参数串放在请求体中发送,而GET方法时将参数追加到URL中发送。

    HTML文件内容:

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
        <script type="text/javascript">
            var xmlHttp;
            function createXMLHttpRequest() {
                if (window.ActiveXObject) {
                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTp");
                }
                else if (window.XMLHttpRequest) {
                    xmlHttp = new XMLHttpRequest();
                }
            }
            function createQueryString() {
                var name = document.getElementById("name").value;
                var birthday = document.getElementById("birthday").value;
    
                var queryString = "name=" + name + "&birthday=" + birthday;
                return queryString;
            }
    
            function doRequestUsingGet() {
                createXMLHttpRequest();
    
                var queryString = "WS.asmx/GetAndPostExample?";
                queryString = queryString + createQueryString() + "&timeStamp=" + new Date().getTime();
                xmlHttp.onreadystatechange = handleStateChange;
                xmlHttp.open("GET", queryString, true);
                xmlHttp.send(null);
            }
            function doRequestUsingPOST() {
                createXMLHttpRequest();
    
                var url = "WS.asmx/GetAndPostExample?timeStamp=" + new Date().getTime();
                var queryString = createQueryString();
                xmlHttp.onreadystatechange = handleStateChange;
                xmlHttp.open("POST", url, true);
                xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-rulencoded;");
                xmlHttp.send(queryString);
            }
            function handleStateChange() {
                if (xmlHttp.readyState == 4) {
                    if (xmlHttp.status == 200) {
                        pareseResults();
                    }
                }
            }
            function pareseResults() {
                var responseDiv = document.getElementById("serverResponse");
                if (responseDiv.hasChildNodes()) {
                    responseDiv.removeChild(responseDiv.childNodes[0]);
                }
                var responseText = document.createTextNode(xmlHttp.responseText);
                responseDiv.appendChild(responseText);
            }
        </script>
    </head>
    <body>
        <h1>
            请输入姓名和生日</h1>
        <table>
            <tbody>
                <tr>
                    <td>
                        姓名:
                    </td>
                    <td>
                        <input type="text" id="name" />
                    </td>
                </tr>
                <tr>
                    <td>
                        生日:
                    </td>
                    <td>
                        <input type="text" id="birthday" />
                    </td>
                </tr>
            </tbody>
        </table>
        <form action="#">
        <input type="button" value="Get" onclick="doRequestUsingGet();" />
        <input type="button" value="Post" onclick="doRequestUsingPOST();" />
        <h2>
            返回:</h2>
        <div id="serverResponse">
        </div>
        </form>
    </body>
    </html>

    后台使用.net写的webserive,发布后远行,文件名为WS.asmx

     [WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        [System.ComponentModel.ToolboxItem(false)]
        // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
        [System.Web.Script.Services.ScriptService]
        public class WS : System.Web.Services.WebService
        {
    
            [WebMethod]
            public string GetAndPostExample()
            {
                Context.Response.ContentType = "text/xml";
                string results = "";
    
    
                if (Context.Request.RequestType == "GET")
                {
                    results += "姓名:" + Context.Request.Params["name"];
                    results += "生日:" + Context.Request.Params["birthday"];
                }
                else
                {
                    byte[] input = Context.Request.BinaryRead(Context.Request.TotalBytes);
                    string source = Encoding.UTF8.GetString(input);
                    string[] sources = source.Split(new char[] { '=', '&' });
                    for (int i = 0; i < sources.Length; i++)
                    {
                        if (sources[i] == "name")
                        {
                            results += "姓名:" + sources[i + 1];
                        }
                        if (sources[i] == "birthday")
                        {
                            results += "生日:" + sources[i + 1];
                        }
                    }
                }
    
                results += "时间:" + Context.Request.Params["timeStamp"];
                results += "方式:" + Context.Request.RequestType;
                return results;
            }
        }

    注意绿色字体部分,需要取消这行的注释,上面的webservice实现有点复杂,可能有较为简单的方法。

    运行效果如下:

    3.使用JSON向服务器发送数据

    JSON建立在两种数据结构基础上:

      1.名/值对集合。在当前编程语言中,这实现了一个对象、记录或字典

      2.值的有序表,这通常实现为一个数组

    JSON对象是名/值对的无序集合。对象以{开始,以}结束,名/值用冒号分隔。JSON数组是一个有序的值的集合,以[开始,以]结束,数组中的值用逗号分隔。

    JSONExample.htm文件

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
        <script type="text/javascript">
            var xmlHttp;
            function createXMLHttpRequest() {
                if (window.ActiveXObject) {
                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTp");
                }
                else if (window.XMLHttpRequest) {
                    xmlHttp = new XMLHttpRequest();
                }
            }
            function doJOSN() {
    
                var car = getCarObject();
                var carAsJSON = JSON.stringify(car);
                createXMLHttpRequest();
                var url = "WS.asmx/JSONExample?timeStamp=" + new Date().getTime();
                xmlHttp.onreadystatechange = handleStateChange;
                xmlHttp.open("POST", url, true);
                xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-rulencoded;");
                xmlHttp.send(carAsJSON)
            }
            function handleStateChange() {
                if (xmlHttp.readyState == 4) {
                    if (xmlHttp.status == 200) {
                        pareseResults();
                    }
                }
            }
            function pareseResults() {
                var responseDiv = document.getElementById("serverResponse");
                if (responseDiv.hasChildNodes()) {
                    responseDiv.removeChild(responseDiv.childNodes[0]);
                }
                var responseText = document.createTextNode(xmlHttp.responseText);
                responseDiv.appendChild(responseText);
            }
            function getCarObject() {
                return new Car("Dodge", "Coronet R/T", 1968, "yellow");
            }
            function Car(make, model, year, color) {
    
                this.make = make;
                this.model = model;
                this.year = year;
                this.color = color;
            }
        </script>
    </head>
    <body>
        <form action="#">
        <input type="button" value="JSON数据" onclick="doJOSN() ;" />
        </form>
        <h2>
            返回:</h2>
        <div id="serverResponse">
        </div>
    </body>
    </html>

    WS.asmx文件中

     [WebMethod]
            public string JSONExample()
            {
                byte[] input = Context.Request.BinaryRead(Context.Request.TotalBytes);
                string source = Encoding.UTF8.GetString(input);
                return source;
            }

    效果:

  • 相关阅读:
    吴恩达深度学习作业
    @Resource
    Hadoop 大数据平台常用组件端口号汇总
    HDFS读写分析
    HDFS基础之NN、SNN、DN
    teamviewer早期版本下载链接
    linux权限说明
    关于Mac VMFusion Centos7虚拟机网络的配置
    mysql开启远程授权
    Java 空值判断的工具类
  • 原文地址:https://www.cnblogs.com/lufangtao/p/2714583.html
Copyright © 2020-2023  润新知