Ajax是“異步javascript和XML”的縮寫已經眾所周知,然而雖然XML是看上去的重要組成部分,它卻不是必須的。一位資深的軟件工程師Douglas Crock ford 開發了一個內建于 javascript 的數據格式,稱為javascript 對象表示(JSON,javascript Object Notation),意思是直接使用Ajax對象來傳遞信息,可以讀作“Jason”。
1. 什么是 JSON
JSON概念很簡單,JSON 是一種輕量級的數據格式,他基于 javascript 語法的子集,即數組和對象表示。由于使用的是 javascript 語法,因此JSON 定義可以包含在javascript 文件中,對其的訪問無需通過基于 XML 的語言來額外解析。不過在使用 JSON 之前,很重要的一點是理解 javascript 中數組及對象字面量的特殊語法。
1.1 數組字面量
數組字面量,是用一對方括號括起一組用逗號隔開的 javascript 值,例如:
復制代碼 代碼如下:
var aNames=["hello", 12, true , null];
[html]
1.2 對象字面量
對象字面量,是通過兩個花括號來定義的。在花括號內可以放置任意數量的“名稱-值”對,定義格 式字符串值”。除了最后一行外,每個“名稱-值”對后必須有一個逗號(這與Perl 中的聯合數組的定義有些類似)。例如:
[code]
var oCar = {
"color": "red",
"doors" : 4,
"paidFor" : true
};
復制代碼 代碼如下:
{comments:[
{
id:1,
author:"someone1",
url:"http://someone1.x2design.net",
content:"hello"
},
{
id:2,
author:"someone2",
url:"http://someone2.x2design.net",
content:"hello"
},
{
id:3,
author:"someone3",
url:"http://someone3.x2design.net",
content:"hello"
}
]};
復制代碼 代碼如下:
var oCar = new Object();
oCar.doors = 4;
oCar.color = "blue";
oCar.year = 1995;
oCar.drivers = new Array("Penny", "Dan" , "Kris");
document.write(JSON.stringify(oCar));
復制代碼 代碼如下:
<comments>
<comment>
<id>1</id>
<author>someone1</author>
<url></url>
<content>hello</content>
</comment>
<comment>
<id>2</id>
<author>someone2</author>
<url></url>
<content>someone1</content>
</comment>
<comment>
<id>3</id>
<author>someone3</author>
<url></url>
<content>hello</content>
</comment>
</comments>
復制代碼 代碼如下:
{comments:[
{
id:1,
author:"someone1",
url:"http://someone1.x2design.net",
content:"hello"
},
{
id:2,
author:"someone2",
url:"http://someone2.x2design.net",
content:"hello"
},
{
id:3,
author:"someone3",
url:"http://someone3.x2design.net",
content:"hello"
}
]};
新聞熱點
疑難解答
圖片精選