Pass a PHP string to a JavaScript variable (and escape newlines)
This question already has an answer here:
Expanding on someone else's answer:
<script>
var myvar = <?php echo json_encode($myVarValue); ?>;
</script>
Using json_encode() requires:
$myVarValue
encoded as UTF-8 (or US-ASCII, of course) Since UTF-8 supports full Unicode, it should be safe to convert on the fly.
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编码
function escapeJavaScriptText($string)
{
return str_replace("n", 'n', str_replace('"', '"', addcslashes(str_replace("r", '', (string)$string), " ..37'")));
}
链接地址: http://www.djcxy.com/p/74144.html
上一篇: 检查一个字符串是否被序列化?