深度剖析JSON功能種種問題進(jìn)行學(xué)習(xí)探討
我們基本的解決方案就是在服務(wù)器端轉(zhuǎn)化前對中文進(jìn)行轉(zhuǎn)碼,比如JSON功能或者進(jìn)行進(jìn)制轉(zhuǎn)換,然后客戶端進(jìn)行相應(yīng)的轉(zhuǎn)換,我們還是需要尋找更快速的方式,或者最好是PHP的JSON擴(kuò)展能夠直接支持中文,那就最好了。
今天我就小試了一下PHP 5.2 內(nèi)置了JSON功能,JSON主要是用于Ajax里面的遠(yuǎn)程訪問時候的數(shù)據(jù)交換格式,可以說是用來在Ajax中取代XML格式的一個輕量級數(shù)據(jù)交換格式,潛力不容小瞧,因?yàn)镚oogle Maps就是拋棄XML而使用JSON的典型例子。#t#
想了解JSON,可以查看這里查看更多文章,同時想了解關(guān)于格式定義可以參考JSON官方網(wǎng)站,關(guān)于更多JSON的資料請Google。
- <?php
- //對象
- class JsonTest{
- var $id = 1;
- var $name = 'heiyeluren';
- var $gender = '男';
- }
- $obj = new JsonTest;
- echo json_encode($obj)."<br /> ";
- //數(shù)字索引數(shù)組
- $arr1 = array(1, 'heiyeluren', '男');
- echo json_encode($arr1)."<br /> ";
- //關(guān)聯(lián)索引數(shù)組
- $arr2 = array("id"=>1, "name"=>'heiyeluren', "gender"=>'男');
- echo json_encode($arr2)."<br /> ";
- //多維數(shù)字索引數(shù)組
- $arr3 = array(array(1, 'heiyeluren', '男'), array(1, 'heiyeluren', '男'));
- echo json_encode($arr3)."<br /> ";
- //關(guān)聯(lián)索引數(shù)組
- $arr4 = array(array("id"=>1, "name"=>'heiyeluren', "gender"=>'男'), array("id"=>1, "name"=>'heiyeluren', "gender"=>'男'));
- echo json_encode($arr4)."<br /> ";
- ?>
- 瀏覽器輸出:
- {"id":1,"name":"heiyeluren","gender":""}
- [1,"heiyeluren",""]
- {"id":1,"name":"heiyeluren","gender":""}
- [[1,"heiyeluren",""],[1,"heiyeluren",""]]
- [{"id":1,"name":"heiyeluren","gender":""},{"id":1,"name":"heiyeluren","gender":""}]
按照JSON功能定義,我們可以發(fā)現(xiàn)上面的幾個特點(diǎn):
1. 純的數(shù)字索引是按照J(rèn)avaScript能夠識別的數(shù)組來存儲的
2. 關(guān)聯(lián)索引數(shù)組是按照J(rèn)avaScript對象的形式來構(gòu)造的
3. 多維關(guān)聯(lián)索引是按照外圍是JavaScript數(shù)組,中間的索引數(shù)組是對象
4. 無法識別中文,所有的中文字符串顯示為空