JSON
Make a table based on JSON data.
JSON : 一個純文字格式,可簡易並方便透過JavaScript與Server資料交換。
<<<When exchanging data between a browser and a server, the data can only be text.
JSON is text, and we can convert any JavaScript object into JSON, and send JSON to the server.
We can also convert any JSON received from the server into JavaScript objects.>>>
<!DOCTYPE html>
<html>
<body>
<h2>Make a table based on JSON data.</h2>
<p id="demo"></p>
<script>
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { "table":"customers", "limit":20 }; //JavaScript物件
//Create JSON string from a JavaScript object.
dbParam = JSON.stringify(obj); //轉化成JSON字串
//Create an XMLHttpRequest Object
xmlhttp = new XMLHttpRequest(); //XMLHttpRequest(AJAX物件):透過此物件,將載入頁面
//Defines a function to be called when the readyState property changes
xmlhttp.onreadystatechange = function() {
/*readyState=> 4: request finished and response is ready
status=>200: "OK"*/
if (this.readyState == 4 && this.status == 200) {
//convert text into a JavaScript object
/*As long as the response from the server is written in JSON format,
you can parse the string into a JavaScript object.*/
myObj = JSON.parse(this.responseText); //將此xmlhttp給的資料,轉成JSON物件
txt += "<table border='1'>"
for (x in myObj) {
txt += "<tr><td>" + myObj[x].name + "</td></tr>"; //取得myObj(JSON物件)屬性的name值
}
txt += "</table>"
document.getElementById("demo").innerHTML = txt;
}
};
//open(method, url, async, user, psw) Specifies the request
xmlhttp.open("POST", "json_demo_db_post.php", true);
//Adds a label/value pair to the header to be sent
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //設定資料內容類型,
// Sends the request to the server
xmlhttp.send("x=" + dbParam); //傳給Server
</script>
</body>
</html>
參考網址: W3School
推薦網址說明: JSON