【发布时间】:2017-02-21 05:42:59
【问题描述】:
这个问题很容易理解和演示。
这段代码运行良好:
<?php
$title = array("dfg","sdfsdg","asfas","Sdfh","Ssdth","Csdgo");
$title_json = json_encode($title);
?>
<script>
var obj = JSON.parse('<?= $title_json; ?>');
console.log(obj);
</script>
这段代码没有:
<?php
$title = array("Is President Trump still using his old Android phone?","Trump sets a dizzying WH pace in first days","Trumps White House Charm Offensive a Contrast to Solitary Obama","The inside story of a basketball teen so tall, he doesn't look real","Scientists say they are closer to making Star Wars holograms","Sperm theft lawsuit leaves appeals court weighing how much a life is worth","Call it Smunday: Heinz pushing to make Super Bowl Monday a national holiday");
$title_json = json_encode($title);
?>
<script>
var obj = JSON.parse('<?= $title_json; ?>');
console.log(obj);
</script>
控制台中的输出错误:Uncaught SyntaxError: missing ) after argument list - (index):20 其中第 20 行是 JSON.parse 之一,如果您查看页面的源代码,则该行显示为:
var obj = JSON.parse('["Is President Trump still using his old Android phone?","Trump sets a dizzying WH pace in first days","Trump's White House Charm Offensive a Contrast to Solitary Obama","The inside story of a basketball teen so tall, he doesn't look real","Scientists say they are closer to making 'Star Wars' holograms","Sperm theft lawsuit leaves appeals court weighing how much a life is worth","Call it 'Smunday': Heinz pushing to make Super Bowl Monday a national holiday"]');
您可能会注意到两个代码示例完全相同,数组甚至具有相同的长度,唯一的区别是第二个中的字符串更长。这是否意味着 JSON 可以解析的字符串存在最大长度?
【问题讨论】:
-
请注意,在浏览器中显示该行的位置,SO 添加到代码中的基于颜色的语法突出显示暗示了问题。
-
现在你可以使用
`(又名反引号)来包装字符串。 (即var obj = JSON.parse(`["Is Pre..."]`); -
@nnnnnn 实际上,如果我使用的 IDE 共享该突出显示,我可能永远不需要问这个问题,我会知道这是撇号。当然,我仍然不知道我什至不需要 JSON.parse 并且会花一段时间试图弄清楚如何逃避撇号。
-
请注意,这些不带引号的答案确实假定您的
json_encodefails silently 永远不会出现这种情况(比如提供了错误的数据)。因为这将导致前端的 js 看起来像var obj = ;,这将抛出Uncaught SyntaxError: Unexpected token ; -
该数组是从数据库中填充的,该数据库本身由表单中的条目填充,因此假设我正确设置了表单验证,应该没有错误数据。
标签: javascript php json