2010-06-22 11 views
6

Ho pour stocker du texte multiligne dans une variable javascript; J'utilise PHP pour attribuer une valeur à une variable javascript.stocker du texte multiligne dans une variable JavaScript

S'il vous plaît voir un exemple de code ci-dessous

<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> 

Je ne veux pas perdre tout characters.How espace blanc peut-il être fait?

+0

en double de http://stackoverflow.com/questions/168214/passe-un-php-string-to-a-javascript-variable-including-escaping-newlines il semble –

Répondre

1

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

1

Utilisez \n où vous voulez casser la ligne.

<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> 

Si vous voulez afficher le texte au navigateur, vous devrez utiliser <br /> plutôt que \n.

Plus d'info:

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

3

Malheureusement, il est un peu ennuyeux que vous ne pouvez pas le faire de cette façon. Vous devrez le faire comme ceci:

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

Ou, en utilisant un truc similaire,

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

essayer

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