如何将多行字符串传递给javascript函数?

问题描述:

我在PHP中的变量如何将多行字符串传递给javascript函数?

$test = "This is a string 
It has multiple lines 
there are three total" ; 

(输出文本区)

我想这个变量传递给JavaScript函数

我在我的PHP文件写这篇

<?php echo "<script language=javascript>convert('$test');</script>"; ?> 

但这造成一个错误“未终止的字符串文字”我该如何解决这个问题?

+1

不相关的问题,但你应该使用'转换('$ test');“; ?> – Gaurav 2011-05-03 11:36:43

+1

使用'\ r \ n',Luke – zerkms 2011-05-03 11:36:50

+0

@Gaurav:'

尝试

$test = "This is a string\nIt has multiple lines\nthere are three total"; 

试试这个:

$test = str_replace($test, "\n", "\\n"); 
+0

它应该是'\\\ n',转换成反斜杠,然后换行。 – duri 2011-05-03 11:46:43

+0

@duri不知道这是真的..我们希望'\ n'能够直接传递给JS函数。 – 2011-05-03 11:52:43

+0

哦,我明白了。我在想另一件事(在行尾添加反斜杠将允许Javascript字符串跨越多行;对此感到抱歉)。 – duri 2011-05-03 12:43:43

<script>convert(<?php echo json_encode($test); ?>);</script> 
+0

它看起来像甚至可以逃脱双引号。非常好的解决方案IMO! – groovenectar 2015-09-28 19:11:22