Pass a PHP string to a JavaScript variable (and escape newlines)

This question already has an answer here:

  • How to pass variables and data from PHP to JavaScript? 16 answers

  • Expanding on someone else's answer:

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

    Using json_encode() requires:

  • PHP 5.2.0 or greater
  • $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

    上一篇: 检查一个字符串是否被序列化?

    下一篇: 将PHP字符串传递给JavaScript变量(并转义换行符)