gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 07:41:17 25 4
gpt4 key购买 nike

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

我是不是漏掉了什么?

最佳答案

您的 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

关于php - 将 PHP 关联数组传递给 JavaScript 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10989121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com