Ajax中数据传递的另一种模式:JSON
使用XML表示:
<comments>
<comment>
<id>1</id>
<author>someone1</author>
<url>http://someone1.x2design.net</url>
<content>hello</content>
</comment>
<comment>
<id>2</id>
<author>someone2</author>
<url>http://someone2.x2design.net</url>
<content>someone1</content>
</comment>
<comment>
<id>3</id>
<author>someone3</author>
<url>http://someone3.x2design.net</url>
<content>hello</content>
</comment>
</comments>
<comment>
<id>1</id>
<author>someone1</author>
<url>http://someone1.x2design.net</url>
<content>hello</content>
</comment>
<comment>
<id>2</id>
<author>someone2</author>
<url>http://someone2.x2design.net</url>
<content>someone1</content>
</comment>
<comment>
<id>3</id>
<author>someone3</author>
<url>http://someone3.x2design.net</url>
<content>hello</content>
</comment>
</comments>
使用JSON:
{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"
}
]};
{
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"
}
]};
很容易发现,使用JSON不仅减少了解析XML解析带来的性能问题和兼容性问题,而且对于javascript来说非常容易使用,可以方便的通过遍历数组以及访问对象属性来获取数据,其可读性也不错,基本具备了结构化数据的性质。不得不说是一个很好的办法,而且事实上google maps就没有采用XML传递数据,而是采用了JSON方案。
JSON的另外一个优势是跨域可行性,例如你在www.xxx.com的网页里使用<script type="text/javascript" src="http://www.yyy.com/some.js"></script>是完全可行的,这就意味着你可以跨域传递信息。而使用XMLHttpRequest却获取不了跨域的信息,这是javascript内部的安全性质所限制的。
JSON看上去很美,是不是就能完全取代XML呢?事实并非如此,而原因就在于XML的优势:通用性。要使服务器端产生语法合格的javascript代码并不是很容易做到的,这主要发生在比较庞大的系统,服务器端和客户端有不同的开发人员。它们必须协商对象的格式,这很容易造成错误。
无论如何,JSON是一个诱人的技术,准备在X2Blog做一个大量的试用。希望届时可以获取大的性能提高。
相 关 文 章
相 关 软 件
本站搜索(搜索结果将在新窗口打开)
