1

i have php variables that is like this

var externalData = '<?php echo $matches[0]; ?>';

I when i load the source code of the page comes like this

var externalData = 'data,data,data,data,data
';

this breaks the javascript code, and browser cant run it.

I want to be like this:

var externalData = 'data,data,data,data,data';

the php output is a full line of a file, so may contains the end of the line. I test it by hand and working, how i can fix this?

4

3 回答 3

4

您可以使用trim(或rtrim) 删除字符串末尾的换行符:

var externalData = "<?php echo trim($matches[0]); ?>";

或者,您可以将整个字符串传递给json_encode

var externalData = <?php echo json_encode($matches[0]); ?>;

这不会删除换行符,但会对其进行编码,结果值将是一个有效的 JS 字符串文字(即所有其他可能破坏代码的字符,例如'or ",也将转义)。

于 2013-08-11T13:16:15.740 回答
0

您还可以使用substr()来摆脱字符串的最后一个字符。

像这样:

var externalData = "<?php echo substr($matches[0], 0, strlen($matches[0]) - 1); ?>";
于 2013-08-11T13:19:49.643 回答
0

也许你应该去掉所有的 HTML

var externalData = "<?php echo strip_tags($matches[0];) ?>");
于 2013-08-11T13:15:21.290 回答