Uncaught SyntaxError: Unexpected end of input

I have a php nested array stored in a variable $myArray , below is how the array looks like (its not a complete output) after var dumping it to the browser.

<?php var_dump($myArray); ?>

The output:

array (size=4)
  'id' => string '162' (length=3)
  'content' => string 'Test content' (length=12)
  'children' => 
    array (size=16)
      0 => 
        array (size=4)
          'id' => string '29208' (length=5)
          'content' => string 'Test content 1' (length=14)
          'children' => 
            array (size=3)
              ...
      1 => 
        array (size=4)
          'id' => string '29215' (length=5)
          'content' => string 'Test content 2' (length=14)
          'children' => 
            array (size=1)
              ...
      2 => 
        array (size=3)
          'id' => string '29220' (length=5)
          'content' => string 'Test Content 3' (length=14)

Reading the variable array from JavaScript as below:

<script type="text/javascript">
var myVar = JSON.parse('<?php json_encode($myArray) ?>');
</script> 

Returns the following error in the console

Uncaught SyntaxError: Unexpected end of input

While debugging the code, I did the following:

Created a new variable and stored some JSON data in it and then JSON parsed it to another variable and then finally consoled the output and it worked fine.

<script type="text/javascript">
var x = '{"id":123,"content":"This is a test content"}';
var myVar = JSON.parse(x);
console.log(myVar); 
</script> 

The output was an object with those values in the console:

Object
    content: "This is a test content"
    id: 123

What am I doing wrong?


var myVar = <?php echo json_encode($myArray) ?>; should do it. No ' characters are needed because the JSON object can be read as written, and no parse is necessary because it's outputting directly onto the page instead of giving it a string


You need to echo out the json object.

<?php json_encode($myArray) ?>

to

<?php echo json_encode($myArray) ?>

Here's a little shorthand trick for you explained here

You can simply do <?=$var?> . It's basically shorthand for echo and only works if the shorthand tag <? is enabled.

So the answer to your question (if shorthand open tags are enabled) you can use this

var myVar = <?=json_encode($myArray)?>; Which is equivalent to what @Dar gave you above but less ugly.

链接地址: http://www.djcxy.com/p/59352.html

上一篇: 获取PHP变量为JavaScript

下一篇: 未捕获的SyntaxError:意外的输入结束