====== Head Rush Ajax 讀書筆記 ======
===== Chapter Five =====
==== JSON(JavaScript Object Notation) ====
http://www.json.com
JSON 只是用 JavaScript 表達某種物件。
比 XML 更像陣列。
大括號 {} 內包含**無次序**的值集合,中括號 [] 表示陣列。
"資料名": 資料值
{"totals": [
{
"boardsSold": 1000,
"bootsSold": 100,
"bindingsSold": 10
}
]};
每一橫排代表 totals[0]~totals[2],每欄資料代表 totals[i].bootsSold。
取出 "Two" 的方法:totals[2].location[1]
{"totals": [
{"location":"Vail", "boardsSold":642, "bootsSold":86, "bindingsSold":19},
{"location":"Santa Fe", "boardsSold":236, "bootsSold":45, "bindingsSold":32}
{"location":["Vail", "Two"], "boardsSold":642, "bootsSold":86, "bindingsSold":19},
]};
==== JavaScript ====
function updatePage() {
if (request.readyState == 4) {
if (request.status == 200) {
// Get the updated totals from the JSON response
var jsonData = eval('(' + request.responseText + ')');
var totalBoards = jsonData.totals[0].boardsSold;
var totalBoots = jsonData.totals[0].bootsSold;
var totalBindings = jsonData.totals[0].bindingsSold;
......
}
==== PHP ====
使用陣列來建立 JSON 可用的資料
require_once('JSON.php');
$json = new Services_JSON();
$vail = array('location' => 'Vail',
'boardsSold' => $vailBoards,
'bootsSold' => $vailBoots,
'bindingsSold' => $vailBindings);
$santaFe = array('location' => 'Santa Fe',
'boardsSold' => $santaFeBoards,
'bootsSold' => $santaFeBoots,
'bindingsSold' => $santaFeBindings);
$totals = array('totals' => array($vail, $santaFe)); // 二維陣列
$output = $json->encode($totals); // 將 PHP 陣列轉成 JSON 結構
print($output);