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

发布于,归属于jquery只剩下板凳啦! 共有574人围观    

在ajax操作中尤其是后台返回的是json数据时,调试上有个烦扰:无法支持在页面输出文本型的json数据,当然可以使用firebug查看,但有没有一种像php的print_r函数,支持打印出数据呢,很遗憾javascript没有print_r,今天在浏览jimpalmer的blog时,发现了解决方案。

javascript中的print_r

  1. function print_r(theObj) {
  2.     var retStr = '';
  3.     if (typeof theObj == 'object') {
  4.         retStr += '<div style="font-family:Tahoma; font-size:7pt;">';
  5.         for (var p in theObj) {
  6.             if (typeof theObj[p] == 'object') {
  7.                 retStr += '<div><b>['+p+'] => ' + typeof(theObj) + '</b></div>';
  8.                 retStr += '<div style="padding-left:25px;">' + print_r(theObj[p]) + '</div>';
  9.             } else {
  10.                 retStr += '<div>['+p+'] => <b>' + theObj[p] + '</b></div>';
  11.             }
  12.         }
  13.         retStr += '</div>';
  14.     }
  15.     return retStr;
  16. }

为了测试此函数的可行性,明河特意做了个demo:

demo中使用了做啥微博的API,获取做啥微博的公共消息,应用到了jsonp,关于jsonp请看明河之前写的一篇教程:《jquery结合JSONP教程

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

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

如果成功就会出现以下图片类似的内容

这个函数在调试时还是相当实用,特此明河写成了一个插件

请打开demo2.html浏览,调用方法如下:

  1. $("#debug").print_r(data);

插件代码如下:

  1. (function($){
  2.     $.fn.print_r = function(json){
  3.         return $(this).each(function(e){
  4.             $(this).html(_print_r(json));
  5.         })
  6.     }
  7.     function _print_r(theObj) {
  8.         var retStr = '';
  9.         if (typeof theObj == 'object') {
  10.             retStr += '<div style="font-size:12px;">';
  11.             for (var p in theObj) {
  12.                 if (typeof theObj[p] == 'object') {
  13.                     retStr += '<div><b>['+p+'] => ' + typeof(theObj) + '</b></div>';
  14.                     retStr += '<div style="padding-left:25px;">' + _print_r(theObj[p]) + '</div>';
  15.                 } else {
  16.                     retStr += '<div>['+p+'] => <b>' + theObj[p] + '</b></div>';
  17.                 }
  18.             }
  19.             retStr += '</div>';
  20.         }
  21.         return retStr;
  22.     }   
  23.     $.print_r = function(json){
  24.         return _print_r(json);
  25.     }
  26. })(jQuery);
(如果您喜欢这篇教程,可以通过支付宝打赏我们1元哦,拜谢!)

跟作者说两句

:wink: :twisted: :roll: :oops: :mrgreen: :lol: :idea: :evil: :cry: :arrow: :?: :-| :-x :-o :-P :-? :) :( :!: 8-O 8)

只剩下板凳了!

  1. hiro

    呵呵,不错不错,有想法!!