请考虑以下代码:
JSON.parse('{"html":{"lang":"en"},"head":"\\n\\t<meta charset=\\"UTF-8\\">\\n\\t<title>Check ScreenShare</title>\\n\\t<link rel=\\"stylesheet\\" href=\\"main.css\\">\\n\\t<script src=\\"main.js\\"></script>\\n","body":"\\n\\t<h1>This is just a test</h1>\\n\\t<p>This is a great thing to do. This is very good.</p>\\n\\n\\n<script src=\\"sendContent.js\\"></script>"}');
这在开发者控制台(firefox)中工作正常,但当我将其包含在像
这样的ntml文件中时,firefox会显示错误<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Check others</title>
</head>
<body>
<!-- <iframe src="" frameborder="0" id="all"></iframe> -->
</body>
<script type="text/javascript">
//var ifrm = document.getElementById('all');
JSON.parse('{"html":{"lang":"en"},"head":"\\n\\t<meta charset=\\"UTF-8\\">\\n\\t<title>Check ScreenShare</title>\\n\\t<link rel=\\"stylesheet\\" href=\\"main.css\\">\\n\\t<script src=\\"main.js\\"></script>\\n","body":"\\n\\t<h1>This is just a test</h1>\\n\\t<p>This is a great thing to do. This is very good.</p>\\n\\n\\n<script src=\\"sendContent.js\\"></script>"}');
//var obj = JSON.parse(JSONstr);
console.log(obj);
</script>
</html>
错误是:
SyntaxError: unterminated string literal
任何有想法如何使其发挥作用的人?
答案 0 :(得分:5)
您无法在字符串块中嵌入字符串</script>
,因为它会结束脚本块。 HTML解析器不知道JavaScript语法,所以它不会关注引号。
改为使用<\/script>
。
我会进一步建议你研究一个模板系统,因为在字符串中嵌入所有标记非常麻烦且容易出错。
答案 1 :(得分:1)
像Pointy和以下article建议的那样:&#34;在HTML结束标记中转义正斜杠。 Hello World!&lt; / div&gt;。&#34;
所以我在向标题标签和两个脚本标签添加三个正斜杠后正确解析了它。
var object = JSON.parse('{"html":{"lang":"en"},"head":"\\n\\t<meta charset=\\"UTF-8\\">\\n\\t<title>Check ScreenShare<\/title>\\n\\t<link rel=\\"stylesheet\\" href=\\"main.css\\">\\n\\t<script src=\\"main.js\\"><\/script>\\n","body":"\\n\\t<h1>This is just a test</h1>\\n\\t<p>This is a great thing to do. This is very good.</p>\\n\\n\\n<script src=\\"sendContent.js\\"><\/script>"}');
console.log(object);
&#13;