2

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

4 回答 4

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

于 2012-06-12T00:33:51.830 回答
2

试试这个:

document.write(topicsjson.toString());
于 2012-06-12T00:26:09.970 回答
1

你可以试试这个例子,转换成可以从 Javascript解析的 XML 。

于 2012-06-12T00:28:48.223 回答
0

使用来源,卢克。不要用 . 读取变量的内容document.write。使用您选择的 Web 浏览器,在此行查看生成的 PHP 文件的源代码:

echo "<script>var topicsjson = $topicsjson; </script>";
于 2012-06-12T01:49:43.690 回答