当作为某些JSON数据的一部分返回时,字符串“”是否会导致任何问题?

时间:2012-09-30 06:28:23

标签: javascript string-literals script-tag

无论如何都不涉及内联脚本。我有一个外部文件脚本,从twitter获取一些JSONP。假设返回的JSONP中表示的对象的属性是一个字符串,其中包含子字符串"</script>"中的某个位置。这可能会导致任何问题,而不会被添加到DOM中吗? (在此之前,它会被清理干净。)

我无法理解它为什么会这样,但HTML解析是出了名的愚蠢和古怪,所以谁知道呢?我知道如果你想在内联脚本中有一个字符串文字,你需要分解它,比如var slashScriptContainingString = 'foo</scr' + 'ipt>bar';再次,我觉得它应该没问题,但只是检查是否有人知道为什么它可能不是。

<!doctype html>
<script src="file.js"></script>

<子> File.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."]);

1 个答案:

答案 0 :(得分:2)

不,字符串文字可以包含您想要的任何内容。只要您不是盲目地尝试设置某事物的innerHTML,字符串就只是一个字符串。您发布的示例是安全的。

您需要在JavaScript源代码中拆分</script>标记的原因是您缺少CDATA块。没有它们,从技术上讲,内联JavaScript中的所有内容都需要针对HTML正确转义。 (<变为&lt;等等。)浏览器对您很好并让它滑动,但内联JavaScript中的</script>变得模棱两可。您应该使用CDATA块来防止这种情况发生。

<script type="text/javascript">
//<![CDATA[
...code...
//]]>
</script>

有关详细信息,请参阅此问题:When is a CDATA section necessary within a script tag?