新行不适用于JavaScript

时间:2014-03-23 18:07:25

标签: javascript newline line-breaks

我将文本传递给JavaScript但新行%0A未被解释,所有文本的结果都显示在一行中。

URL:

https://www.example.com/post.php?v=1&text=hello%0Aworld%0Atest

代码:

<?php
$postText = $_GET["text"]; 
?>  

<!DOCTYPE HTML>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    </head>
    <body>
    <script type="text/javascript">
      var options = {
        prefilltext: '<?php echo $postText;?>',
      };
    </script>
    </body>
    </html>

我尝试nl2brstr_replace没有任何成功:

$postText = str_replace("%0A", "\n", $postText);
$postText = nl2br($postText); 

我需要更改什么才能使换行符正常工作?

1 个答案:

答案 0 :(得分:2)

在您输出JavaScript字符串文字时,只需将文本转出即可。

最简单的方法就是使用json_encode

  var options = {
    prefilltext: <?php echo json_encode($postText);?>
  };

请注意没有引号,它会添加它们。

为什么json_encode输出要包含在JavaScript中的字符串?因为JSON是JavaScript语法的子集,所以任何有效的JSON也都是有效的JavaScript源代码(假设它是预期表达式的地方,例如赋值的右侧)。如果$postText是PHP字符串,json_encode($postText)将返回JSON字符串文字的文本,该文字可用作JavaScript字符串文字。


旁注:您的代码在属性初始值设定项后也有一个悬空逗号,例如:

  var options = {
    prefilltext: 'the text would be here',
    // This is the dangling comma -------^
  };

...我已删除了,因为older versions of IE will choke就已经删除了