javascript
2010-06-22 62 views 6 likes 
6

Ho將多行文本存儲在javascript變量中;將多行文本存儲在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> 

樣本代碼,我不想失去任何空白characters.How才能做到這一點?

+0

http://stackoverflow.com/questions的重複/ 168214/pass-a-php-string-to-a-javascript-variable-including-escaping-newlines看起來好像 – 2010-06-22 04:55:57

回答

1

this answer<?php echo json_encode($foo); ?>(PHP> = 5.2)

1

使用\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

3

可悲的是,因爲你不能這樣做的有點討厭。你必須做這樣的:

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"); 
0

試試這個

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