zoukankan      html  css  js  c++  java
  • jQuery插件之json篇

    今天来说说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()四个方法的配对使用问题.很简单但是在实际应用中却非常实用.

  • 相关阅读:
    man date
    Python---Tkinter---贪吃蛇
    Python---TKinter项目实战---屏保
    虚拟化之kvm --(vnc控制台)
    cisco和华为的设备如何设置命令不分页显示
    liunx之Centos6.8杀毒软件的安装
    Liunx系统命令sed的使用
    自动运维之网络设备割接配置按预定步骤操作
    mutt+msmtp实现在shell环境中发送电子邮件
    windowns下excel2013快速生成月报表
  • 原文地址:https://www.cnblogs.com/luluping/p/1441495.html
Copyright © 2011-2022 走看看