Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
541 views
in Technique[技术] by (71.8m points)

php - 将PHP字符串传递给JavaScript变量(并转义换行符)[复制](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包含引号或换行符时,这不起作用。)

  ask by David Laing translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Expanding on someone else's answer:

(扩展别人的答案:)

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

Using json_encode() requires:

(使用json_encode()需要:)

  • PHP 5.2.0 or greater

    (PHP 5.2.0或更高版本)

  • $myVarValue encoded as UTF-8 (or US-ASCII, of course)

    ($myVarValue编码为UTF-8(当然是US-ASCII))

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

(由于UTF-8支持完整的Unicode,因此动态转换应该是安全的。)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...