将PHP关联数组传递给JavaScript时出错

时间:2012-06-12 00:23:03

标签: php javascript arrays json

我正在尝试将此关联数组传递给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 ) ) 

在PHP文件中:

$topicsjson=json_encode($topics);
echo "<script>var topicsjson = $topicsjson; </script>";

在JavaScript文件中:

document.write(topicsjson);

它给了我这个结果:

[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

我在这里错过了什么吗?

4 个答案:

答案 0 :(得分:4)

您的PHP会生成以下JavaScript:

<script>var topicsjson = [{"topicid":38,"topic":"Dad"},{"topicid":6,"topic":"What did you eat?"},{"topicid":4},{"topic":"What have you done?"}]; </script>

使用两个for循环来迭代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/>");
    }
}

演示: jsFiddle

答案 1 :(得分:2)

请改为尝试:

document.write(topicsjson.toString());

答案 2 :(得分:1)

您可以尝试this example,转换为XML,可以解析from Javascript

答案 3 :(得分:0)

Use the source, Luke。请勿使用document.write读取变量的内容。使用您选择的Web浏览器,请参阅此行生成的PHP文件的源代码:

echo "<script>var topicsjson = $topicsjson; </script>";