最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

PHP string to JavaScript - Stack Overflow

programmeradmin2浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论