将 PHP 字符串传递给 JavaScript 变量(并转义换行符) [英] Pass a PHP string to a JavaScript variable (and escape newlines)

查看:28
本文介绍了将 PHP 字符串传递给 JavaScript 变量(并转义换行符)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将 PHP 字符串编码为 JavaScript 变量的最简单方法是什么?

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. I need the contents of this string to be put into a JavaScript variable.

通常,我只会在 PHP 文件中构建我的 JavaScript,就像这样:

Normally, I would just construct my JavaScript in a PHP file, à la:

<script>
  var myvar = "<?php echo $myVarValue;?>";
</script>

但是,当 $myVarValue 包含引号或换行符时,这不起作用.

However, this doesn't work when $myVarValue contains quotes or newlines.

推荐答案

扩展别人的答案:

<script>
  var myvar = <?php echo json_encode($myVarValue); ?>;
</script>

使用 json_encode() 需要:

  • PHP 5.2.0 或更高版本
  • $myVarValue 编码为 UTF-8(当然也可以是 US-ASCII)
  • PHP 5.2.0 or greater
  • $myVarValue encoded as UTF-8 (or US-ASCII, of course)

由于 UTF-8 支持完整的 Unicode,因此即时转换应该是安全的.

Since UTF-8 supports full Unicode, it should be safe to convert on the fly.

请注意,因为 json_encode 会转义正斜杠,所以即使是包含 </script> 的字符串也会被安全转义以使用脚本块进行打印.

Note that because json_encode escapes forward slashes, even a string that contains </script> will be escaped safely for printing with a script block.

这篇关于将 PHP 字符串传递给 JavaScript 变量(并转义换行符)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆