PHP string to JavaScript - Stack Overflow

I am trying to copy the string $str = 'thisismystring';to a JavaScript variable like sovar st

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.

Share Improve this question edited Jan 24, 2012 at 22:10 Daniel Fischer 184k18 gold badges317 silver badges435 bronze badges asked Jan 24, 2012 at 20:36 Dvir LevyDvir Levy 8,12812 gold badges41 silver badges61 bronze badges 1
  • 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
Add a ment  | 

5 Answers 5

Reset to default 5

You 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

相关推荐

  • PHP string to JavaScript - Stack Overflow

    I am trying to copy the string $str = 'thisismystring';to a JavaScript variable like sovar st

    1天前
    60

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信