没有涉及任何内联脚本。我有一个外部文件脚本,它从 twitter 获取一些 JSONP。假设返回的 JSONP 中表示的对象的属性是一个字符串,其中某处包含子字符串 "</script>"
.如果根本不添加到 DOM 中,这会不会本身导致任何问题? (在那之前它会被擦洗干净。)
我不明白为什么会这样,但是 HTML 解析是出了名的古怪古怪,所以谁知道呢?我知道如果你想在内联脚本中包含一个字符串文字,你需要将它分解,比如 var slashScriptContainingString = 'foo</scr' + 'ipt>bar';
同样,我觉得它应该没问题,但只是想看看是否有人知道为什么会这样。
<!doctype html>
<script src="file.js"></script>
文件.js:
var f = function(twobj) {
console.log(twobj);
doOtherStuffWith(twobj);
}
<script src="https://api.twitter.com/statuses/user_timeline/user.json?callback=f"></script>
返回的 JSONP:
f(["this is an object, returned as part of the JSONP response, except it contains a string literal with the substring \"</script>\". Is this a problem? Note: I haven't said anything about injecting this string in the DOM in any way shape or form. I can't think of a reason why it might be, but I'd just like to be sure."]);
最佳答案
不,字符串文字可以包含您想要的任何内容。只要您不盲目尝试设置 innerHTML
的东西,一个字符串只是一个字符串。您发布的示例是安全的。
您需要拆分 </script>
的原因JavaScript 源代码中的标记是您缺少 CDATA block 。如果没有它们,从技术上讲,您的内联 JavaScript 中的所有内容都需要针对 HTML 进行正确转义。 ( <
变成 <
等)浏览器对你很好,让它滑动,但是 </script>
内联 JavaScript 变得模棱两可。您应该使用 CDATA block 来防止此类事情发生。
<script type="text/javascript">
//<![CDATA[
...code...
//]]>
</script>
有关详细信息,请参阅此问题:When is a CDATA section necessary within a script tag?
关于javascript - 当作为某些 JSON 数据的一部分返回时,字符串 "</script>"会导致任何问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12659184/