JSON概念很简单,就是服务器直接生成Javascript语句,客户端获取后直接用eval方法来获得这个对象,这样就可以省去解析XML的性损失。

例如:

使用XML表示:

代码:
<items>
 <item>
  <id>1</id>
  <author>Jackson</author>
  <url>http://www.richweb.cn</url>
  <content>Welcome to RichWeb.cn</content>
 </item>
 <item>
  <id>2</id>
  <author>Relkn</author>
  <url>http://www.richweb.cn</url>
  <content>RichWeb.cn关注互联网新技术</content>
 </item>
 <item>
  <id>3</id>
  <author>Kvogend</author>
  <url>http://www.richweb.cn</url>
  <content>RichWeb.cn关注WEB2.0</content>
 </item>
</items>

 

使用JSON:

代码:
{items:[
 {
  id:1,
  author:"Jackson",
  url:"http://www.richweb.cn",
  content:"Welcome to RichWeb.cn"
 },
 {
  id:2,
  author:"Relkn",
  url:"http://www.richweb.cn",
  content:"RichWeb.cn关注互联网新技术"
 },
 {
  id:3,
  author:"Kvogend",
  url:"http://www.richweb.cn",
  content:"RichWeb.cn关注WEB2.0"
 }
]};

 

JSON不仅减少了解析XML解析带来的性能问题和兼容性问题,而且对于Javascript来说非常容易使用,可以方便的通过遍历数组以及访问对象属性来获取数据,其可读性也不错,基本具备了结构化数据的性质。不得不说是一个很好的办法,而且事实上google maps就没有采用XML传递数据,而是采用了JSON方案。

JSON的另外一个优势是"跨域性",例如你在www.richweb.cn的网页里使用

<script type="text/javascript" src="" target="_blank">http://www.yyy.com/some.js">

是完全可行的,这就意味着你可以跨域传递信息。而使用XMLHttpRequest却获取不了跨域的信息,这是Javascript内部的安全性质所限制的。