首頁  >  文章  >  web前端  >  jQuery處理json資料傳回數組和輸出的方法_jquery

jQuery處理json資料傳回數組和輸出的方法_jquery

WBOY
WBOY原創
2016-05-16 16:10:121248瀏覽

本文實例講述了jQuery處理json資料傳回數組和輸出的方法。分享給大家供大家參考。具體實作方法如下:

複製程式碼 程式碼如下:
/*print the json object
 *
 *$("selector").print_r_json(json,opts) : return formatted string (and print)
 *sprint_r_json : just return the string;
 *print_r_json : return the formatted string and print json data
 *contribute 明河
 *
 *auth iorichina
 *
 *example:
 *3 ways to use it
 *
 *
*/
$.fn.print_r_json = function(json,options){
    if(typeof(json)!="object") return false;
    var opts = $.extend({},$.fn.print_r_json.defaults,options);
    var data = '';
    if(opts.if_print)
    {
        data = $.sprint_r_json(json)
        $(this).html('
'+(opts.return_array?'Array':'JSON-DATA')+'
'+data);
    }
    if(opts.array)
    {
        return $.json_to_array(json);
    }
    return data;
};
$.fn.print_r_json.defaults =
{
    if_print : false,//if print or just return formatted string
    return_array : true //return an Array
};
$.extend({
    print_r_json : function(json)
    {
        if(typeof(json)=="object")
        {
            var text='
{
';
          document.write('
{
');
          for(var p in json)
          {
            if(typeof(json[p])=="object")
            {
              document.write('
["'+p+'"] => ');
                text+='
["'+p+'"] => '+$.print_r_json(json[p])+'
';
              document.write('
');
            }
            else
            {
                text+='
['+((/^\d+$/).test(p)?p:('"'+p+'"'))+'] => "'+json[p]+'"
';
              document.write('
['+p+'] => '+json[p]+'
');
            }
          } 
          text+='
}
';
          document.write('
}
');
          return (テキスト);
        }
        それ以外
        {
            document.write(json);
            return (json);
        }
    }、
    sprint_r_json : 関数(json)
    {
        if(typeof(json)=="オブジェクト")
        {
          var text = '
{
';
          for(json の var p)
          {
            if(typeof(json[p])=="オブジェクト")
            {
              text = '
["' p '"] => ' $.sprint_r_json(json[p]) '
';
            }
            それ以外
            {
              text = '
[' ((/^d $/).test(p)?p:('"' p '"')) '] => "' json[p] '"
';
            }
          }
          text = '
}
';
          return (テキスト);
        }
        それ以外
        {
            return (json);
        }
    }、
    json_to_array : function(json)
    {
        if(typeof(json)=="オブジェクト")
        {
          var text = new Array();
          for(json の var p)
          {
            if(typeof(json[p])=="オブジェクト")
            {
              text[p] = $.json_to_array(json[p]);
            }
            それ以外
            {
              text[p] = json[p];
            }
          }
          return (テキスト);
        }
        それ以外
        {
            return (json);
        }
    }
});

ここで説明されている大規模な jQuery プログラムの設計が役立つことを望みます。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn