简体   繁体   English

从PHP解析javascript的问题

[英]problems parsing JSON in javascript from PHP

Here is my PHP array: 这是我的PHP数组:

$entries = array(
    1420934400 => array(
        'entry' => 'I think I liked it.',
        'data' => 'some'
    ),
    1452470400 => array(
        'entry' => 'Turkey is much better. Tastes more like chicken.',
        'data' => 'no calls'
    ));

Then I convert to JSON 然后我转换为JSON

$entries = json_encode($entries);

This produces the string: 这会产生字符串:
{"1420934400":{"entry":"I think I liked it.","data":"some"},"1452470400":{"entry":"Turkey is much better. Tastes more like chicken.","data":"no calls"}}

...which I believe is valid JSON. ...我相信它是有效的JSON。 But when I try to access in JavaScript: 但是当我尝试使用JavaScript访问时:

<script>
    var fetchedEntries = JSON.parse(<?php echo $entries ?>);
    console.log('entries: %o', fetchedEntries);
</script>

I get the following error: 我收到以下错误:

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data SyntaxError:JSON.parse:JSON数据的第1行第2列的意外字符

Can anyone see where I'm going wrong? 谁能看到我哪里出错了?

You don't need JSON.parse in JS since JSON can be directly interpreted by JS (it is called JavaScript Object Notation for a reason ;-). 你不需要JS中的JSON.parse,因为JSON可以直接由JS解释(因为某种原因,它被称为JavaScript Object Notation ;-)。 Do

var fetchedEntries = <?php echo $entries ?>;

When you receive the JSON data as a string, then JSON.parse is appropriate. 当您以字符串形式接收JSON数据时,JSON.parse是合适的。 For example, this works too: 例如,这也适用:

var fetchedEntries = JSON.parse( "<?php echo json_encode( $array_or_obj ); ?>" );

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

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