忽然感觉很久没上博了,今日上来一看居然将近一个月没写新文章了,再不“生产”两篇,感觉也太对不起自己的博了。最近正好项目里有用到一些 JSON 的部分,于是今天就写一点使用心得来与大家分享一下吧。
说道 JSON 还真是一个好东西,一个字,就是“快”。前一段我把一个原先提供返回 XML 的服务改成 JSON 以后,速度竟然提高了将近 3 倍,特别是与前端 Ajax 客户端集成使用,真可谓之“天作之合”。但是 JSON 对中文的支持一直以来为人们所诟病,网上关于这方面的问题也是一抓一大把,但是不要误解,实际上这个问题并没有想象的那么麻烦,以下石头会通过一个实例来说明一下这个问题。
废话少说,代码先行:
client.php :
< html >< head >< meta http-equiv ="content-type" content ="text/html; charset=utf-8" />
< title > JSON - TEST </ title >
< script type ="text/javascript" src ="/js/prototype.js" ></ script >
< script language ="JavaScript" type ="text/javascript" > ... <!--
function chat () ...{
// try {
var url = 'server.php';
new Ajax.Request(url, ...{
method: 'post',
asynchronous: true,
onLoading : function()...{},
onSuccess: function(transport, json) ...{
// Remainder of the code
alert(json.name+' : '+json.desc+' : '+json.attach)
}
});
// } catch (e) {}
}
function chat2 () ...{
// try {
var url = 'server.php?ret=1';
new Ajax.Request(url, ...{
method: 'post',
asynchronous: true,
onLoading : function()...{},
onSuccess: function(req) ...{
// Remainder of the code
var json = parseJSON(req);
alert(json.name+' : '+json.desc+' : '+json.attach)
}
});
// } catch (e) {}
}
function parseJSON (request) ...{
try ...{ return eval('(' + request.responseText + ')'); } catch (e) ...{}
}
--> </ script >
</ head >
< body >
< a href ="#" onclick ="chat();" > Get Chat By Prototype </ a >< br />
< a href ="#" onclick ="chat2();" > Get Chat By Self </ a >
< div id ="chatbox" ></ div >
</ body >
</ html >
server.php :
include_once ( ' JSON.php ' );
// create a new instance of Services_JSON
$json = new Services_JSON();
// convert a complexe value to JSON notation, and send it to the browser
$value = array ( ' name ' => ' stone ' , ' desc ' => iconv ( ' gb2312 ' , ' utf-8 ' , ' 哈哈 ' ) , ' attach ' => array ( 1 , 2 , ' baz ' ));
$output = $json -> encode( $value );
if ( isset ( $_REQUEST [ ' ret ' ])) {
// header('Content-type: text/x-json; charset=utf-8');
echo $output ;
// prints: ["foo","bar",[1,2,"baz"],[3,[4]]]
} else {
header ( ' X-JSON: ( ' . $output . ' ) ' );
}
// accept incoming POST data, assumed to be in JSON notation
$input = file_get_contents ( ' php://input ' , 1000000 );
$value = $json -> decode( $input );
?>
第一种方法我们把分析 JSON 返回信息的任务也全权交由“万能”的 Prototype 来做,但是 Prototype 是通过自己定义的 HTTP Header 信息里的 X-JSON 头来传递信息,而据我所知 IE 里的 HTTP Header 长度默认是有限制的,所以我还是推荐大家用第二种方法:用 parseJSON 方法来自助处理 JSON 的数据,既简单又有效 ... 分析好后就可以用了解析出来的 JavaScript Object 来做你想要做的排列咯 ... 说到中文问题,实际上也很简单,只需要把要传递的数据做一下 utf-8 转换即可,我这里用 php 做例子所以用 iconv 函数就可以了,Java 的话,更不用说了,编码转换就是他的强项呢。
OK ... 写完收工,下班回家,又是一个周末,Happy Time :)
原文链接: http://blog.csdn.net/shagoo/article/details/1712004