Mar*_*mer 1 javascript php json
这个问题很容易理解和证明.
这段代码工作正常:
<?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>
Run Code Online (Sandbox Code Playgroud)
此代码不会:
<?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>
Run Code Online (Sandbox Code Playgroud)
在控制台中输出错误: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"]');
Run Code Online (Sandbox Code Playgroud)
您可能会注意到两个代码示例完全相同,数组甚至具有相同的长度,唯一的区别是字符串在第二个中更长.这是否意味着JSON可以解析的字符串有最大长度?
您的JSON数据包含'.因此,如果将该数据注入'分隔的字符串文字中,该字符串文字将过早关闭并导致语法错误.简单的例子:
var foo = '{"key": "This key's value"}';
Run Code Online (Sandbox Code Playgroud)
您应该注意到,如果您查看生成JavaScript源代码.
这里没有必要使用JSON.parse.注入的JSON可以解释为JavaScript对象/数组文字:
var obj = <?= $title_json; ?>;
Run Code Online (Sandbox Code Playgroud)
另请参见:如何将变量和数据从PHP传递到JavaScript?
| 归档时间: |
|
| 查看次数: |
102 次 |
| 最近记录: |