I am trying to copy the string
$str = '
this
is
my
string';
to a JavaScript variable like so
var str1 = '<?php echo $str ?>';
but when I do, I get an error
Uncaught SyntaxError: Unexpected token ILLEGAL
If you are asking yourself why I'm doing this,
I create a <table>
with PHP and insert it to the $str
variable and want to later use it in a JavaScript function.
I am trying to copy the string
$str = '
this
is
my
string';
to a JavaScript variable like so
var str1 = '<?php echo $str ?>';
but when I do, I get an error
Uncaught SyntaxError: Unexpected token ILLEGAL
If you are asking yourself why I'm doing this,
I create a <table>
with PHP and insert it to the $str
variable and want to later use it in a JavaScript function.
-
Whenever, you need to place a string available in a PHP variable in a JavaScript code generated by the PHP, you should use json_encode() function. For your example:
var str1 = <?php echo json_encode($str) ?>;
– Susam Pal Commented Jan 24, 2012 at 20:51
5 Answers
Reset to default 5You should just use json_encode()
from http://www.php/manual/en/function.json-encode.php
Example:
var str1 = <?php echo json_encode($str) ?>;
It takes care of converting newlines to \n
, escaping any other special characters as necessary, preserve spaces, etc.
Example output for your string:
var str1 = "\n this\n is\n my\n string";
Problem is EOL character in your PHP strng.
Use it like this (after replacing all EOL characters with a space):
var str1 = '<?php echo str_replace("\n", " ", $str) ?>';
Javascript does not except multiline strings. You can put a backslash before the end of each line if you want to keep it looking like that.
JavaScript doesn't like multiline string literals or have a here-doc syntax. Try changing your string to
$str = ' \
this \
is \
my \
string';
Have you tried this?
var str1 = '<?php echo $str; ?>';
Notice the semicolon.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744939864a4602253.html
评论列表(0条)