我有这个代码
$ref = addslashes(htmlspecialchars(json_encode($value)));
echo '<script>var message_store_'.$key.'=$.parseJSON('.$ref.');alert(message_store_'.$key.');</script>';
echo '<div class="message_entry" id ="message_entry'.$key.'" onclick="open_up_thread(\''.$ref.'\',\''.$key.'\');">'.$key.'</div>';
$recent = end($value);
echo '<div id ="recent_message_log_entry'.$key.'"><div>'.$recent['message'].'</div><div>'.$recent['date_posted'].'</div></div>';
我在将数组存储在全局 JavaScript 变量中时遇到问题。 但我的 div onclick 事件工作正常,数组已转换为我想要的,并且函数 open_up_thread 正在解析编码的 JSON 对象。
我需要在 onclick 事件触发之前跟踪该数组(在 onclick 之后很容易,因为它已经转换)。
那么我如何实现将 php 数组作为 php 中的 JSON 存储到全局 javascript 对象中。
以及为什么我让 onclick 工作但变量不起作用的任何原因
提前致谢
最佳答案
删除 $.parseJSON()
函数并删除 htmlspecialchars
和 addslashes
:
$ref = json_encode($value);
echo '<script>var message_store_'.$key.'='.$ref.';alert(message_store_'.$key.');</script>';
JSON是一种可以直接解析为变量的格式。
关于php - 如何将嵌套的 php 数组放入 javascript 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18112690/