在ajax操作中尤其是后台返回的是json数据时,调试上有个烦扰:无法支持在页面输出文本型的json数据,当然可以使用firebug查看,但有没有一种像php的print_r函数,支持打印出数据呢,很遗憾javascript没有print_r,今天在浏览jimpalmer的blog时,发现了解决方案。
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;
- }
为了测试此函数的可行性,明河特意做了个demo:
demo中使用了做啥微博的API,获取做啥微博的公共消息,应用到了jsonp,关于jsonp请看明河之前写的一篇教程:《jquery结合JSONP教程》
调用函数输出的代码如下:
- $(function(){
- $.getJSON("http://api.zuosa.com/statuses/public_timeline.json?callback=?", function(data) {
- $("#debug").html(print_r(data));
- });
- })
如果成功就会出现以下图片类似的内容

这个函数在调试时还是相当实用,特此明河写成了一个插件
请打开demo2.html浏览,调用方法如下:
- $("#debug").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);

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