zoukankan      html  css  js  c++  java
  • Fetching data with Ajax小例子

    ajax获取数据示例:

    示例1

    通过ajax获取txt文件里面的内容示例:

    <html>  

    <head>    

    <title>Ajax at work</title>

    <script type="text/javascript">    

       var XMLHttpRequestObject = false;

          if (window.XMLHttpRequest) {       

      XMLHttpRequestObject = new XMLHttpRequest();     

      } else if (window.ActiveXObject) {  

           XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");    

       }

          function getData(dataSource, divID)       {        

    if(XMLHttpRequestObject) {     

          var obj = document.getElementById(divID);       

        XMLHttpRequestObject.open("GET", dataSource);

              XMLHttpRequestObject.onreadystatechange = function() {     

            if (XMLHttpRequestObject.readyState == 4 &&   XMLHttpRequestObject.status == 200) {

                  obj.innerHTML = XMLHttpRequestObject.responseText;         

             }     

          }

           XMLHttpRequestObject.send(null);       

      }   

    }    

    </script>

      </head>

      <body>

        <H1>Fetching data with Ajax</H1>

        <form>   

        <input type = "button" value = "Display Message"         onclick = "getData('data.txt', 'targetDiv')"/>  

       </form>

    <img src="Image1.jpg"       onmouseover="getData('sandwiches.txt', 'targetDiv')" onmouseout="getData('data.txt', 'targetDiv')">

        <img src="Image2.jpg"       onmouseover="getData('pizzas.txt', 'targetDiv1')" onmouseout="getData('data.txt', 'targetDiv1')">

        <img src="Image3.jpg"       onmouseover="getData('soups.txt', 'targetDiv2')" onmouseout="getData('data.txt', 'targetDiv2')">

        <div id="targetDiv">       <p>Welcome to my restaurant!</p>     </div>  

         <div id="targetDiv1">       <p>Welcome to my restaurant!</p>     </div>   

        <div id="targetDiv2">       <p>Welcome to my restaurant!</p>     </div>

      </body>

    </html>

    示例2

    通过ajax获取XML文件里面的内容示例:

    innerHTML.html文件代码:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     <html>
    <head>
    <title>Using responseText with innerHTML</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="Search for Today's Activities" onClick="startRequest()" />
        </form>
        <div id="results"></div>
    </body>
    </html>

    innerHTML.xml文件代码:

    <?xml version="1.0" encoding="UTF-8"?>

    <table border="1">
        <tbody>
            <tr>
                <th>Activity Name</th>
                <th>Location</th>
                <th>Time</th>
            </tr>
            <tr>
                <td>Waterskiing</td>
                <td>Dock #1</td>
                <td>9:00 AM</td>
            </tr>   
            <tr>
                <td>Volleyball</td>
                <td>East Court</td>
                <td>2:00 PM</td>
            </tr>   
            <tr>
                <td>Hiking</td>
                <td>Trail 3</td>
                <td>3:30 PM</td>
            </tr>   
        </tbody>
    </table>

    运行效果:

    示例3

    通过ajax解析xml数据

    parseXML.html文件里面的代码:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html >
    <head>
    <title>Parsing XML Responses with the W3C DOM</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", "parseXML.xml", true);
        xmlHttp.send(null);
    }
    function handleStateChange() {
        if(xmlHttp.readyState == 4) {
            if(xmlHttp.status == 200) {
                if(requestType == "north") {
                    listNorthStates();
                }
                else if(requestType == "all") {
                    listAllStates();
                }
            }
        }
    }
    function listNorthStates() {
        var xmlDoc = xmlHttp.responseXML;
        var northNode = xmlDoc.getElementsByTagName("north")[0];
        var northStates = northNode.getElementsByTagName("state");
        outputList("Northern States", northStates);
    }
    function listAllStates() {
        var xmlDoc = xmlHttp.responseXML;
        var allStates = xmlDoc.getElementsByTagName("state");
       
        outputList("All States in Document", allStates);
    }
    function outputList(title, states) {
        var out = title;
        var currentState = null;
        for(var i = 0; i < states.length; i++) {
            currentState = states[i];
            out = out + " - " + currentState.childNodes[0].nodeValue;
        }
        alert(out);
    }
    </script>
    </head>
    <body>
        <h1>Process XML Document of U.S. States</h1>
        <br/><br/>
        <form action="#">
            <input type="button" value="View All Listed States" onclick="startRequest('all');"/>
            <br/><br/>
            <input type="button" value="View All Listed Northern States" onclick="startRequest('north');"/>
        </form>
    </body>
    </html>

    parseXML.xml文件里面的代码:

    <?xml version="1.0" encoding="UTF-8"?>
    <states>
        <north>
            <state>Minnesota</state>
            <state>Iowa</state>
            <state>North Dakota</state>
        </north>
        <south>
            <state>Texas</state>
            <state>Oklahoma</state>
            <state>Louisiana</state>
        </south>
        <east>
            <state>New York</state>
            <state>North Carolina</state>
            <state>Massachusetts</state>
        </east>
        <west>
            <state>California</state>
            <state>Oregon</state>
            <state>Nevada</state>
        </west>
    </states>

    运行效果如图所示:

    示例4

    动态更新显示内容:

    dynamicContent.html主要代码如下:

     <script type="text/javascript">

    createXMLHttpRequest(){ 

     获取XMLHttpRequest代码……

    }

      function doSearch() {

        createXMLHttpRequest();

        xmlHttp.onreadystatechange = handleStateChange;

        xmlHttp.open("GET", "dynamicContent.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 property = null;     var address = "";     var price = "";     var comments = "";  

           var min=document.getElementsByName("min");  

       var max=document.getElementsByName("max");  

       var minval=min[0].options[min[0].selectedIndex].value; // 选中值  

       var maxval=max[0].options[max[0].selectedIndex].value; // 选中值

        minval=parseFloat(minval);     maxval=parseFloat(maxval);

        var properties = results.getElementsByTagName("property");  

       for(var i = 0; i < properties.length; i++) {

            property = properties[i];  

           address = property.getElementsByTagName("address")[0].firstChild.nodeValue;

            price = property.getElementsByTagName("price")[0].firstChild.nodeValue;  

           comments = property.getElementsByTagName("comments")[0].firstChild.nodeValue;

            price=parseFloat(price);

          if(price>=minval && price<=maxval){ 

           addTableRow(address, price, comments);

          };

        }  

           var header = document.createElement("h2");

        var headerText = document.createTextNode("Results:");

        header.appendChild(headerText);

        document.getElementById("header").appendChild(header);

        document.getElementById("resultsTable").setAttribute("border", "1"); }

    function addTableRow(address, price, comments) {

        var row = document.createElement("tr");

        var cell = createCellWithText(address);

        row.appendChild(cell);

        cell = createCellWithText(price);

        row.appendChild(cell);

        cell = createCellWithText(comments);

        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>

      <h1>Search Real Estate Listings</h1>

      <form action="#">

        Show listings from

            <select name="min">

                <option value="50000">$50,000</option>

                <option value="100000">$100,000</option>

                <option value="150000">$150,000</option>

            </select >

            to

            <select name="max">

                <option value="100000">$100,000</option>

                <option value="150000">$150,000</option>

                <option value="200000">$200,000</option>

            </select>

        <input type="button" value="Search" onclick="doSearch();"/> 

         </form>

      <span id="header">   </span>

      <table id="resultsTable" width="75%" border="0">     <tbody id="resultsBody">     </tbody>   </table>

    </body>

    </html>

    dynamicContent.xml代码如下:

    <?xml version="1.0" encoding="UTF-8"?>
    <properties>
     <property>
            <address>812 Gwyn Ave</address>
            <price>90000</price>
            <comments>Quiet, serene neighborhood</comments>
        </property>  
        <property>
            <address>812 Gwyn Ave</address>
            <price>100000</price>
            <comments>Quiet, serene neighborhood</comments>
        </property>   
        <property>
            <address>3308 James Ave S</address>
            <price>110000</price>
            <comments>Close to schools, shopping, entertainment</comments>
        </property>   
        <property>
            <address>98320 County Rd 113</address>
            <price>155000</price>
            <comments>Small acreage outside of town</comments>
        </property>   
    </properties>

    运行效果:

    顺便附上GET和POST方法的相关代码:

    <script type="text/javascript">

    var xmlHttp;

    function createXMLHttpRequest() {

         获取XMLHttpRequest代码……

    }  

       function createQueryString() {

        var firstName = document.getElementById("firstName").value;  

       var middleName = document.getElementById("middleName").value;  

       var birthday = document.getElementById("birthday").value;

        var queryString = "firstName=" + firstName + "&middleName=" + middleName  + "&birthday=" + birthday;  

       return queryString;

    }

    function doRequestUsingGET() {

        createXMLHttpRequest();

        var queryString = "data.txt?";

        queryString = queryString + createQueryString()

            + "&timeStamp=" + new Date().getTime();  

        xmlHttp.onreadystatechange = handleStateChange;  

       xmlHttp.open("GET", queryString, true);

        xmlHttp.send(null);

    }

    function doRequestUsingPOST() {

        createXMLHttpRequest();

        var url = "data.txt?timeStamp=" + new Date().getTime();  

       var queryString = createQueryString();

       xmlHttp.open("POST", url, true);

        xmlHttp.onreadystatechange = handleStateChange;

        xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    /*  含义是表示客户端提交给服务器文本内容的编码方式 是URL编码,即除了标准字符外,每字节以双字节16进制前加个“%”表示,
    setRequestHeader方法只是XMLHTTP为添加或修改HTTP头提供的一个接口方法而已, 至于里面的值则是HTTP协议的含义.  */

            xmlHttp.send(queryString);

    }

        function handleStateChange() {

        if(xmlHttp.readyState == 4) {

            if(xmlHttp.status == 200) {

                parseResults();

            }

        }

    }

    function parseResults() {

        var responseDiv = document.getElementById("serverResponse");

        if(responseDiv.hasChildNodes()) {

            responseDiv.removeChild(responseDiv.childNodes[0]);  

       }   

         var responseText = document.createTextNode(xmlHttp.responseText);

        responseDiv.appendChild(responseText); }

    post xml文件

    function createXML() {

        var xml = "<pets>";

        var options = document.getElementById("petTypes").childNodes;

        var option = null;

        for(var i = 0; i < options.length; i++) {  

           option = options[i];

            if(option.selected) {

                xml = xml + "<type>" + option.value + "</type>";

            }

        }

        xml = xml + "</pets>";     return xml;

    }

    function sendPetTypes() {

        createXMLHttpRequest();

        var xml = createXML();

        var url = "data.txt?timeStamp=" + new Date().getTime();

        xmlHttp.open("POST", url, true);

        xmlHttp.onreadystatechange = handleStateChange;  

       xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

            xmlHttp.send(xml);

    }

    </script>

     发送json数据到后台:

    <script type="text/javascript" src="json.js"></script>

    function doJSON() {
        var car = getCarObject();
        //Use the JSON JavaScript library to stringify the Car object
        var carAsJSON = JSON.stringify(car);
        alert("Car object as JSON: " + carAsJSON);
        var url = "data.txt?timeStamp=" + new Date().getTime();
        createXMLHttpRequest();
        xmlHttp.open("POST", url, true);
        xmlHttp.onreadystatechange = handleStateChange;
        xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");   
        xmlHttp.send(carAsJSON);
    }

    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; }

  • 相关阅读:
    [opencv] 生成标定棋盘格
    [opencv] cmake编译opencv并去窗口边框
    [opencv] matlab生成opencv可读的xml
    [matlab] vc++和matlab混合编程
    全息摄影
    [opencv&opengl]多窗口显示
    CPLEX
    ios读取设备姿态并传输
    python: 基本知识记录
    css: position的使用;
  • 原文地址:https://www.cnblogs.com/XiaoyangBoke/p/3565143.html
Copyright © 2011-2022 走看看