本文翻译自:Pass a PHP string to a JavaScript variable (and escape newlines) [duplicate]
This question already has an answer here: 这个问题在这里已有答案:
What is the easiest way to encode a PHP string for output to a JavaScript variable? 编码PHP字符串以输出到JavaScript变量的最简单方法是什么?
I have a PHP string which includes quotes and newlines. 我有一个PHP字符串,其中包括引号和换行符。 I need the contents of this string to be put into a JavaScript variable. 我需要将此字符串的内容放入JavaScript变量中。
Normally, I would just construct my JavaScript in a PHP file, à la: 通常,我只是在PHP文件中构建我的JavaScript,àla:
<script>
var myvar = "<?php echo $myVarValue;?>";
</script>
However, this doesn't work when $myVarValue
contains quotes or newlines. 但是,当$myVarValue
包含引号或换行符时,这不起作用。
#1楼
参考:https://stackoom.com/question/hl8/将PHP字符串传递给JavaScript变量-并转义换行符-复制
#2楼
Don't run it though addslashes()
; 不要运行addslashes()
; if you're in the context of the HTML page, the HTML parser can still see the </script>
tag, even mid-string, and assume it's the end of the JavaScript: 如果您在HTML页面的上下文中,HTML解析器仍然可以看到</script>
标记,甚至是中间字符串,并假设它是JavaScript的结尾:
<?php
$value = 'XXX</script><script>alert(document.cookie);</script>';
?>
<script type="text/javascript">
var foo = <?= json_encode($value) ?>; // Use this
var foo = '<?= addslashes($value) ?>'; // Avoid, allows XSS!
</script>
#3楼
<script>
var myVar = <?php echo json_encode($myVarValue); ?>;
</script>
or 要么
<script>
var myVar = <?= json_encode($myVarValue) ?>;
</script>
#4楼
用JSON编码
#5楼
If you use a templating engine to construct your HTML then you can fill it with what ever you want! 如果您使用模板引擎来构建HTML,那么您可以随意填写它!
Check out XTemplates . 查看XTemplates 。 It's a nice, open source, lightweight, template engine. 它是一个不错的开源轻量级模板引擎。
Your HTML/JS there would look like this: 您的HTML / JS看起来像这样:
<script>
var myvar = {$MyVarValue};
</script>
#6楼
htmlspecialchars 用htmlspecialchars
Description 描述
string htmlspecialchars ( string $string [, int $quote_style [, string $charset [, bool $double_encode ]]] )
Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. 某些字符在HTML中具有特殊意义,如果要保留其含义,则应由HTML实体表示。 This function returns a string with some of these conversions made; 此函数返回一个字符串,其中包含一些转换; the translations made are those most useful for everyday web programming. 所做的翻译是对日常网络编程最有用的翻译。 If you require all HTML character entities to be translated, use htmlentities() instead. 如果要翻译所有HTML字符实体,请改用htmlentities()。
This function is useful in preventing user-supplied text from containing HTML markup, such as in a message board or guest book application. 此功能可用于防止用户提供的文本包含HTML标记,例如在留言板或留言簿应用程序中。
The translations performed are: 执行的翻译是:
* '&' (ampersand) becomes '&'
* '"' (double quote) becomes '"' when ENT_NOQUOTES is not set.
* ''' (single quote) becomes ''' only when ENT_QUOTES is set.
* '<' (less than) becomes '<'
* '>' (greater than) becomes '>'
http://ca.php.net/htmlspecialchars http://ca.php.net/htmlspecialchars