最新的Web開發教程
 

網絡構建 - 通過HTTP的獲取數據


從頭開始建立第六部分網站:使用HTTP獲取數據。


我們將要做什麼

在本章中,我們將:

  • 從使用服務器的HTTP獲取數據

數據

以下數據可以由PHP服務器來提供:

http://www.w3ii.com/website/customers.html

{
"records": [
  {
    "Name" : "Alfreds Futterkiste",
    "City" : "Berlin",
    "Country" : "Germany"
  },
  {
    "Name" : "Berglunds snabbkop",
    "City" : "Lulea",
    "Country" : "Sweden"
  },
  {
    "Name" : "Centro comercial Moctezuma",
    "City" : "Mexico D.F.",
    "Country" : "Mexico"
  },
  {
    "Name" : "Ernst Handel",
    "City" : "Graz",
    "Country" : "Austria"
  },
  {
    "Name" : "FISSA Fabrica Inter. Salchichas S.A.",
    "City" : "Madrid",
    "Country" : "Spain"
  },
  {
    "Name" : "Galeria del gastronomo",
    "City" : "Barcelona",
    "Country" : "Spain"
  },
  {
    "Name" : "Island Trading",
    "City" : "Cowes",
    "Country" : "UK"
  },
  {
    "Name" : "Koniglich Essen",
    "City" : "Brandenburg",
    "Country" : "Germany"
  },
  {
    "Name" : "Laughing Bacchus Wine Cellars",
    "City" : "Vancouver",
    "Country" : "Canada"
  },
  {
    "Name" : "Magazzini Alimentari Riuniti",
    "City" : "Bergamo",
    "Country" : "Italy"
  },
  {
    "Name" : "North/South",
    "City" : "London",
    "Country" : "UK"
  },
  {
    "Name" : "Paris specialites",
    "City" : "Paris",
    "Country" : "France"
  },
  {
    "Name" : "Rattlesnake Canyon Grocery",
    "City" : "Albuquerque",
    "Country" : "USA"
  },
  {
    "Name" : "Simons bistro",
    "City" : "Kobenhavn",
    "Country" : "Denmark"
  },
  {
    "Name" : "The Big Cheese",
    "City" : "Portland",
    "Country" : "USA"
  },
  {
    "Name" : "Vaffeljernet",
    "City" : "Århus",
    "Country" : "Denmark"
  },
  {
    "Name" : "Wolski Zajazd",
    "City" : "Warszawa",
    "Country" : "Poland"
  }
]
}
注意上述文件是JSON格式。

更改客戶頁面使用HTTP

demoweb文件夾,更改文件customers.html客戶

將下面的代碼裡面的文件:

customers.html客戶

<!DOCTYPE html>
<html>
<head>
  <title>Customers</title>
  <link href="site.css" rel="stylesheet">
</head>
<body>

<nav id="nav01"></nav>

<div id="main">
  <h1>Customers</h1>
  <div id="id01"></div>
  <footer id="foot01"></footer>
</div>

<script src="script.js"></script>

<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://www.w3ii.com/website/customers.html";

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        myFunction(xmlhttp.responseText);
    }
}
xmlhttp.open("GET", url, true);
xmlhttp.send();

function myFunction(response) {
    var obj = JSON.parse(response);
    var arr = obj.records;
    var i;
    var out = "<table><tr><th>Name</th><th>City</th><th>Country</th></tr>";

    for(i = 0; i < arr.length; i++) {
        out += "<tr><td>" +
        arr[i].Name +
        "</td><td>" +
        arr[i].City +
        "</td><td>" +
        arr[i].Country +
        "</td></tr>";
    }

    out += "</table>"
    document.getElementById("id01").innerHTML = out;
}
</script>

</body>
</html>
試一試»

閱讀更多

了解更多關於JSON在我們的JSON教程