简体   繁体   English

无法从PHP json_encode解析JS中的JSON对象

[英]Unable to parse JSON object in JS from PHP json_encode

I have an array in PHP, which I pack to JSON object with _json_encode(..)_ . 我在PHP中有一个数组,我用_json_encode(..)_打包到JSON对象。 Then I send it to JS function as parameter. 然后,将其作为参数发送给JS函数。 When I want to parse the object in Javascript with eval(..) nothing happens (there is an error behind the curtains I guess). 当我想用eval(..)解析Javascript中的对象时,什么也没发生(我猜是幕后有错误)。 What could be wrong? 有什么事吗
Code: 码:

<script type="text/javascript">
    function testFun(inArr) {
      var obj=eval('('+inArr+')');
      alert(obj.m); //alert(obj) also doesnt work
    }
</script>  


//PHP
$spola_array = array('m' => 1, 'z' => 2);
$json_obj=json_encode($spola_array);
echo '<script type="text/javascript">testFun('.$json_obj.');</script>';

It's already parsed since you're outputting it as an object literal and not a string. 由于您将其输出为对象文字而不是字符串,因此已经对其进行了解析。 That will look like: 看起来像:

<script type="text/javascript">testFun({m: 1, z: 2});</script>

So in your function, it's just: 因此,在您的函数中,它只是:

alert(inArr.m) //1

You would only need to parse it if it were a string: 您只需解析它是一个字符串即可:

<script type="text/javascript">testFun('{m: 1, z: 2}');</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM