假设服务器已经向浏览器返回了一个符合json语法的字符串,那我们如何将这个特殊的字符串转换为一个JS对象呢?
我们可以利用prototype库中的一个函数evalJSON( )来将符合json语法的字符串转换为一个JS对象。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<script src="prototype1.6.js">
</script>
</head>
<body>
<script>
function test(){
var str='{"name":"tom","age":20}';
//alert(typeof str);
var person=str.evalJSON();
alert(person.name+" "+person.age);
}
function test2(){
var str='[{"name":"tom","age":20},{"name":"green","age":30}]';
var persons=str.evalJSON();
alert(persons[1].name+" "+persons[1].age);
}
</script>
<a href="javascript:test()">test</a><br>
<a href="javascript:test2()">test2</a>
</body>
</html>