Berikut adalah contoh JSON yang membaca data daripada web server melalui PHP dan MySQL:
File Customers.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | <!DOCTYPE html> <html> <head> <style> h1 { border-bottom: 3px solid #cc9900; color: #996600; font-size: 30px; } table, th , td { border: 1px solid grey; border-collapse: collapse; padding: 5px; } table tr:nth-child(odd) { background-color: #f1f1f1; } table tr:nth-child(even) { background-color: #ffffff; } </style> </head> <body> <h1>Customers</h1> <div id="id01"></div> <script> var xmlhttp = new XMLHttpRequest(); var url = "http://www.w3schools.com/website/customers_mysql.php"; xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { myFunction(xmlhttp.responseText); } } xmlhttp.open("GET", url, true); xmlhttp.send(); function myFunction(response) { var arr = JSON.parse(response); var i; var out = "<table>"; 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> |
Dibawah adalah kod PHP yang berlaku di server:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <?php header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json; charset=UTF-8"); $conn = new mysqli("myServer", "myUser", "myPassword", "Northwind"); $result = $conn->query("SELECT CompanyName, City, Country FROM Customers"); $outp = "["; while($rs = $result->fetch_array(MYSQLI_ASSOC)) { if ($outp != "[") {$outp .= ",";} $outp .= '{"Name":"' . $rs["CompanyName"] . '",'; $outp .= '"City":"' . $rs["City"] . '",'; $outp .= '"Country":"'. $rs["Country"] . '"}'; } $outp .="]"; $conn->close(); echo($outp); ?> |
Sekian,
****************************************************
Disediakan Oleh : Zainimar binti Zulkifli
Sumber : http://www.w3schools.com/json/json_example.asp
****************************************************
0 comments:
Post a Comment