繁体   English   中英

将多行文本存储在JavaScript变量中

[英]store multi-line text in a JavaScript variable

Ho将多行文本存储在javascript变量中;

我正在使用PHP为javascript变量赋值。

请参阅下面的示例代码

<html>
 <head>
 <title> New Document </title>
 <?php

  $foo = " this is a 
               multiline statement";
 ?>

 <script> 
  bar = '<?php print $foo;?>';
  alert(bar);
 </script>
 </head>
  <body>
 </body>
</html>

我不想丢失任何空白字符。这怎么办?

可悲的是,它有点烦人,因为你不能这样做。 你必须这样做:

var str = [
    "Hello, this is a       \n"
    "multiline\n",
    "       string."
].join("");

或者,使用类似的技巧,

var str = [
    "Hello, this ",
    "     is a multiline ",
    "string separated by new lines ",
    " with each array index"
].join("\n");

在想要打破线的位置使用\\n

<html>
 <head>
 <title> New Document </title>
 <?php

  $foo = " this is a \n
               multiline statement";
 ?>

 <script> 
  bar = '<?php print $foo;?>';
  alert(bar);
 </script>
 </head>
  <body>
 </body>
</html>

如果要将文本输出到浏览器,则必须使用<br />而不是\\n

更多信息:

http://www.c-point.com/javascript_tutorial/special_characters.htm

这个回答<?php echo json_encode($foo); ?> <?php echo json_encode($foo); ?> (PHP> = 5.2)

试试这个

var JsString = "<?php 
echo str_replace(array("\n","\r","\r\n"),'','YOUR 
MULTI LINE 
STRING');?>";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM