开发者

Javascript: Write Console.debug() output to browser?

开发者 https://www.devze.com 2022-12-12 14:05 出处:网络
I need to be able to take any JSON data and print the key/valu开发者_如何转开发e pairs. (something similar to print_r() in PHP)

I need to be able to take any JSON data and print the key/valu开发者_如何转开发e pairs.

(something similar to print_r() in PHP)

Is this even possible with javascript?


I usually just quickly create a log function that allows you change the logging method. Write enablers/disablers or comment out to choose the options.

function log(msg){
  if (window.console && console.log) {
    console.log(msg); //for firebug
  }
  document.write(msg); //write to screen
  $("#logBox").append(msg); //log to container
}

Update: Info on Firebug's Console API

Update: Added check for non firebug browsers.


Yes, you can process a surprising amount of info through alert, and you can also use it for debugging.

Here is a print_r equivalent for javascript also.

function print_r(theObj){
  if(theObj.constructor == Array ||
     theObj.constructor == Object){
    document.write("<ul>")
    for(var p in theObj){
      if(theObj[p].constructor == Array||
         theObj[p].constructor == Object){
document.write("<li>["+p+"] => "+typeof(theObj)+"</li>");
        document.write("<ul>")
        print_r(theObj[p]);
        document.write("</ul>")
      } else {
document.write("<li>["+p+"] => "+theObj[p]+"</li>");
      }
    }
    document.write("</ul>")
  }
}

good luck with your project!


I would recommend you to get a JSON parsing library like JSON2 for being able to "stringify" your objects, then you can simply:

var myString = JSON.stringify(myObject);

myString will now contain a string representation of myObject.

But if it's for debugging purposes I would recommend you to get a JavaScript debugger, like Firebug, you get a lot of useful functions in the Console API.


can you simply use the following:

 document.write('<h2>Your Text and or HTML here.</h2>'); 


FireBug is a great tool! Indispensable! I found it eliminates the need to write debug data into my pages and I can view JSON all day long.


I need to be able to take any JSON data and print the key/value pairs.

Well then print the JSON data. JSON is a notation, not an object. If you have JSON data, you already have all you need. If you want it to be a little more fancy, you might want to add a linebreak after every "\s*,.

If you want to deconstruct an object, it's not possible unless you're using JavaScript, as ECMAScript can't create cyclic references in a single object literal. If this is JavaScript-only, then you can use uneval(object), which will make use of sharp variables. (eg. ({x:#1={y:#1#}})).

0

精彩评论

暂无评论...
验证码 换一张
取 消