简体   繁体   中英

parseJson is running into an unexpected error (Unexpected identifier)

This is all in the same script. I know the difference between ajax and serverside code. I have php interwoven in this javascript script as follows:

<script>
    <?php
        $json_string = json_encode(array("agent_table" => "<span style='float: left;'></span>"));
    ?>

    var response = $.parseJSON('<?php echo $json_string; ?>');
</script>

But parseJson is complaining of an error. The error disappears when I remove the styling from the span .

The error is 'Unexpected identifier'. This is in Chrome.

You have ' characters in your data. These will continue to be represented as literal ' characters in the JSON.

You are embedding your JSON directly into a JavaScript string, and that string is delimited by ' characters. The first ' that appears as data in the JSON will terminate the JS string.

This is a general problem when embedding on data format in another. You are embedding JSON in JavaScript in HTML.

Your options:

  • Replace every instance of ' in the JSON with \\' (so they mean "Apostrophe" instead of "End of JS string")
  • Treat the JSON as a JavaScript object literal instead of trying to munge it into a string which you run it through a JSON parser.

The latter option is the sane one (so long as your goal doesn't involve proving that PHP can generate valid JSON).

var response = <?php echo $json_string; ?>;

You don't need to worry about further escaping for inserting into the HTML because the only sequence you need to worry about (inside a script element) is </script> and PHP's json_encode will output <\\/script> for that anyway.

May be it?

<script>
<?php
$json_string = json_encode(array(
                               "agent_table"=> '<span style="float: left;"></span>'
                           ));
?>
var response = <?php echo $json_string;?>;
</script>

try it!!!

<script>
<?php
$json_string = json_encode(array('agent_table' => addslashes('<span style="float: left;"></span>')));
?>

var response = $.parseJSON('<?php echo $json_string; ?>');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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