[英]How to use php json_encoded array in jQuery
In my php code, I have 在我的PHP代码中,我有
<?php
$test = json_encode($array);//$array is a valid multidimensional array
?>
I am passing this variable to a javascript function and I am trying to set this variable to javascript. 我将此变量传递给javascript函数,并且试图将此变量设置为javascript。
<script>
var test = "<?php echo $test;?>";
</script>
(To clarify I am using codeigniter framework and for simplicity I did not use how I am sending the variable to the page) (为澄清起见,我使用的是codeigniter框架,为简单起见,我没有使用将变量发送到页面的方式)
But when I execute the above code, I am getting 但是当我执行上面的代码时,我得到
Uncaught SyntaxError: Unexpected identifier
I have checked all my syntax. 我已经检查了所有语法。
Thank you in advance. 先感谢您。
Don't put the decoded json array inside double quotes in the javascript. 不要将已解码的json数组放在javascript中的双引号中。 Change to this.
改成这个。
var test = <?php echo $test;?>;
It's not required to wrap the output of json_encode in quotes, otherwise it will be interpreted as a string. 不需要将json_encode的输出用引号引起来,否则它将被解释为字符串。 At which point you'll need to decode it within JavaScript.
此时,您需要在JavaScript中对其进行解码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.