I have several situations where I need to pass multi-dimensional PHP arrays into Javascript/jQuery. The PHP function json_encode() seems to do this rather well. I’ve seen some examples that use $.parseJSON, but I’m not sure if this is for IE6 compatibility or some other issue. Can anyone elaborate if this is the correct format to use in JavaScript. Assume this is javascript/jQuery as part of a PHP view.
var sections = <?php echo json_encode($sections); ?>;
Or, perhaps this would be better?
var sections = <?php if (!empty($sections)) { echo json_encode($sections); } else { echo "new Array()"; } ?>;
Or, do I need $.parseJSON? It seems to throw an error.
var sections = $.parseJSON(<?php echo json_encode($sections); ?>);
Does anyone know of any IE6 issues I should be aware of? If I should use parseJSON(), is it used with single or double quotes?
Thanks in advance,
Jeff Walters
I don’t know anything about IE, but as long as you aren’t dealing with JSON strings in JavaScript you will not need any
parseJSONfunction. Just putting them out into the script text should be fine.