dougang1965 2014-09-06 13:09
浏览 104
已采纳

在PHP中构建JSON并在<script>中回显它时转义字符

I'm trying to build a large JSON string in PHP and then echo it to the client like this. My problem is that the PHP function json_encode isn't properly escaping characters for the purposes of javascript.

Here's my data:

my_table
------------------------------------------------------------------
|       title       |                 description                |
------------------------------------------------------------------
| Something's "Fun" | Hello[invisible carriage return char]World |
------------------------------------------------------------------

There are three characters in these data that need to be escaped: the single quote, the double quote, and the carriage return character.

Here's my php that turns the data into json (after I put the data into an object):

$array = array(
   'title' => obj->title,
   'desc' => obj->description
);

$json = json_encode($array);

I then take my json string with the "properly" escaped characters and echo it to the client from my view like this:

<script>
   var jsonString = '<?php echo $json; ?>';
   var obj = JSON.parse(jsonString);
</script>

But when the page loads, my browser (Chrome) pushes an "Unexpected identifier" error because this is what the script tag actually looks like:

<script>
   var jsonString = '{"title":"Something's \"Fun\"","desc":"Hello
World"}';
   var obj = JSON.parse(jsonString);
</script>

From the perspective of js the double quote is the only one that's escaped correctly. The single quote isn't escaped at all and js freaks out at the .

BTW: manually escaping the single quote doesn't work. And I don't know what to do with the to get js to recognize it.

  • 写回答

1条回答 默认 最新

  • dongzhiju0324 2014-09-08 11:54
    关注

    This is simply a misunderstanding of what json is: written literally in a format that can create a javascript object. So once a json string is echo'd to the page in a <script> tag there is no need to parse it. The code in the view should look like this:

    <script>
       var obj = <?php $json; ?>;
    </script>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?