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 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 虚心请教几个问题,小生先有礼了
  • ¥30 截图中的mathematics程序转换成matlab