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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀