javascript仿php的print_r函数输出json数据

来源:互联网 发布:line是什么软件 编辑:程序博客网 时间:2024/06/16 18:13

转载:http://www.36ria.com/2196


javascript中的print_r


    function print_r(theObj) {        var retStr = '';        if (typeof theObj == 'object') {            retStr += '<div style="font-family:Tahoma; font-size:7pt;">';            for (var p in theObj) {                if (typeof theObj[p] == 'object') {                    retStr += '<div><b>['+p+'] => ' + typeof(theObj) + '</b></div>';                    retStr += '<div style="padding-left:25px;">' + print_r(theObj[p]) + '</div>';                } else {                    retStr += '<div>['+p+'] => <b>' + theObj[p] + '</b></div>';                }            }            retStr += '</div>';        }        return retStr;    }

调用函数输出的代码如下:

    $(function(){        $.getJSON("http://api.zuosa.com/statuses/public_timeline.json?callback=?", function(data) {            $("#debug").html(print_r(data));        });           })

插件代码如下:

    (function($){        $.fn.print_r = function(json){            return $(this).each(function(e){                $(this).html(_print_r(json));            })        }        function _print_r(theObj) {            var retStr = '';            if (typeof theObj == 'object') {                retStr += '<div style="font-size:12px;">';                for (var p in theObj) {                    if (typeof theObj[p] == 'object') {                        retStr += '<div><b>['+p+'] => ' + typeof(theObj) + '</b></div>';                        retStr += '<div style="padding-left:25px;">' + _print_r(theObj[p]) + '</div>';                    } else {                        retStr += '<div>['+p+'] => <b>' + theObj[p] + '</b></div>';                    }                }                retStr += '</div>';            }            return retStr;        }           $.print_r = function(json){            return _print_r(json);        }    })(jQuery);