PHP的JSON类库我使用的是Services_JSON ,没什么特别的优点,也没什么明显的缺点,对付用足矣。
建立文件data.php :
<?php
include( "JSON.php" );
$data = array(
array( 'name' => mb_convert_encoding ( '老王' , 'UTF-8' , 'GBK' ), 'age' => '28' ),
array( 'name' => mb_convert_encoding ( '小黄' , 'UTF-8' , 'GBK' ), 'age' => '27' )
);
$json = new Services_JSON ();
echo $json -> encode ( $data ) ;
?>
Javascript解析JSON我使用的是Jquery ,直接使用Javascript的eval则有个地方要注意:
var myObject = eval('(' + myJSONtext + ')');
具体可查看下面的参考链接。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>demo</title>
<script type="text/javascript" src="jquery-latest.pack.js"></script>
<script>
$(function(){
$.getJSON("data.php ", function(json){
for(var i = 0; i < json.length; i++)
{
alert("姓名:" + json[i].name);
alert("年龄:" + json[i].age);
}
});
});
</script>
</head>
<body>
</body>
</html>