博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

jQuery插件之json篇

Posted on 2009-04-22 17:30  linFen  阅读(8089)  评论(0编辑  收藏  举报

今天来说说jquery的json插件, json(javascript object notation)是一种轻量级的数据交换格式, 易于阅读和编写, 同时也易于机器解析和生成. 关于更多json的知识可以查看这里. jquery的json插件查看这里

这里以前几天写的一个程序为例来说明一下.
首页现在HTML页面中引用2个JS文件

<script type="text/javascript"  src="/js/jquery-1.2.6.min.js"></script>
<script type="text/javascript" src="/js/jquery.json.js"></script>

假设我们现在有一个全局文字对象变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// 全局文字对象变量
gts = { "p":[],
"imgsrc":"",
"avatar":{"show":"0", "width":"73", "height":"85", "x":"0", "y":"0"},
"shantu":{"make":"0", "type":"1", "val":""}
};

// 默认文字对象
dt = function(_txtid, _cnname) {
this.txtid = _txtid;
this.cnname = _cnname;

this.fontface = "fzzhiyi.ttf";
this.fontsize = "14";
this.fontcolor = "#FF0099";
this.altercolor = "#ffffff";
this.x = "0";
this.y = "0";
this.wordlimit = "10";
this.textdirection = "0";
this.effect = "0";
this.jump = "0";
this.txt = "示范文字";
this.isstroke = "0";
this.strokecolor = "#ff0000";
this.borderx = "1";
this.bordery = "1";
this.angle = "0"
}

// 文字对象数组中添加一个默认文字对象
gts.p.push(new dt('txt1', '文字1'));


在前台页面通过AJAX向后台PHP脚本POST数据:

1
2
3
4
5
6
7
// 请注意发送过去的p参数是如何转换为json格式的=>$.toJSON(gts)
$.post('Handler.php', {'action':'preview', 'p':$.toJSON(gts), 'avPath':$('#avPath').val()}, function(res){
// 解码json使用$.evalJSON(res)
var obj = $.evalJSON(res);
// .....处理结果
alert(obj.success);
});

后台页面在接收到数据后是如何处理的呢? 请看PHP代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// ...这里忽略参数处理代码
if ($action == 'preview') {
// json_decode函数很好很强大. 注意true参数, 将直接返回数组
$params = json_decode(stripSlashes($_POST['p']), true);
$imgsrc = $params['imgsrc'];

$img = new Imagick('../'.$imgsrc);
$wh = $img->getImagePage();
$width = $wh['width'];
$height = $wh['height'];

$txtParams = $params['p'];

// var_dump($txtParams);

foreach($txtParams as $k => $v) {
// ....
}
// ...... 返回结果
$res = array('success' => 'ok');
echo json_encode($res);

明白了吗? POST过来的参数经过json_decode解码后为一个数组, 然后我们就可以直接使用这个数组了.
其实说来说去就是$.toJSON(str), $.evalJSON(str), json_decode(), json_encode()四个方法的配对使用问题.很简单但是在实际应用中却非常实用.