Membangun sebuah situs web dari awal Bagian VI:. Mengambil data dengan Http.
Apa yang akan kita lakukan
Dalam bab ini kita akan:
- Mengambil data dari server menggunakan Http
Data
Data berikut dapat diberikan oleh server 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"
}
]
}
file di atas dalam format JSON. |
Ubah Halaman Pelanggan menggunakan Http
Dalam folder demoweb, mengubah customers.html berkas.
Masukan kode berikut di dalam file tersebut:
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>
Cobalah sendiri " Baca lebih banyak
Baca lebih lanjut tentang JSON di kami JSON Tutorial .