I'm trying to pass this associative array to JavaScript:
Array ( [0] => Array ( [topicid] => 38 [topic] => Dad ) [1] => Array ( [topicid] => 6 [topic] => What did you eat? ) [2] => Array ( [topicid] => 4 [topic] => What have you done? ) [3] => Array ( [topicid] => 43 [topic] => He ) [4] => Array ( [topicid] => 28 [topic] => I doubt it ) [5] => Array ( [topicid] => 10 [topic] => What made you feel good ) [6] => Array ( [topicid] => 12 [topic] => Say to yourself ) [7] => Array ( [topicid] => 29 [topic] => I doubt myself ) )
In PHP file:
$topicsjson=json_encode($topics);
echo "<script>var topicsjson = $topicsjson; </script>";
In JavaScript file:
document.write(topicsjson);
It gives me this result:
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Am I missing something here?
4 Answers 4
Your PHP generates JavaScript like the following:
<script>var topicsjson = [{"topicid":38,"topic":"Dad"},{"topicid":6,"topic":"What did you eat?"},{"topicid":4},{"topic":"What have you done?"}]; </script>
Use two for loops to iterate over the contents of topicsjson.
var length = topicsjson.length;
for (var i = 0; i < length; i++) {
for (var key in topicsjson[i]) {
document.write(key + ": " + topicsjson[i][key] + "<br/>");
}
}
Demo: jsFiddle
answered Jun 12, 2012 at 0:33
creemama
6,6753 gold badges23 silver badges26 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Felix Kling
It's an array of objects. The way how to iterate over object properties is to use a
for...in loop. This as nothing to do with arrays. If any, then arrays in JavaScript are actually objects. So don't get too confusing here ;)creemama
@FelixKling Thanks for the feedback. I simplified my answer.
Ivan Wang
Thanks, well explained answer.
Try this instead:
document.write(topicsjson.toString());
answered Jun 12, 2012 at 0:26
Thomas Fussell
4683 silver badges9 bronze badges
2 Comments
Felix Kling
That will give the same output.
toString() is called implicitly.Ivan Wang
sadly, @FelixKling is right. toString gives no different answers.
You could try this example, converting to XML, which can be parsed from Javascript.
answered Jun 12, 2012 at 0:28
NoBugs
9,34816 gold badges91 silver badges159 bronze badges
Use the source, Luke. Don't read the contents of the variable with document.write. Using your web browser of choice, see the source code of the generated PHP file at this line:
echo "<script>var topicsjson = $topicsjson; </script>";
answered Jun 12, 2012 at 1:49
vz0
33k7 gold badges47 silver badges80 bronze badges
Comments
default
topicsjsonis an array of objects. The default string representation of objects is[object Object]. Since you are usingdocument.write, all elements of the array are converted to strings. If you want to inspect the variable, then use the console andconsole.log. There is nothing wrong with your data, just the way you look at it.