如何在不破坏javascript代码的情况下给javascript换行换行符?
问题描述:
我需要在以下情况下在javascript中添加一个中断。如何在不破坏javascript代码的情况下给javascript换行换行符?
<?php
$str_alert = "";
if(isset($case1)){
$str_alert .= "have case1 \n";
}
if(isset($case2)){
$str_alert .= "have case2 \n";
}
if(isset($case3)){
$str_alert .= "have case3 \n";
}
if(!empty($str_alert)){
?>
<script type="text/javascript" >
$(document).ready(function(){
alert("<?=$str_alert?>");
});
</script>
打破它的JavaScript代码,并显示错误
SyntaxError: unterminated string literal
请给我任何解决方案
答
添加\
逃避PHP \n
。尝试以下代码
<?php
$str_alert = "";
if(isset($case1)){
$str_alert .= "have case1 \\n";
}
if(isset($case2)){
$str_alert .= "have case2 \\n";
}
if(isset($case3)){
$str_alert .= "have case3 \\n";
}
if(!empty($str_alert)){
?>
<script type="text/javascript" >
$(document).ready(function(){
alert("<?=$str_alert?>");
});
</script>
答
的JavaScript字符串不能打破跨换行符没有逃逸()。看到这个问题的详细解答:
How do I break a string across more than one line of code in JavaScript?
答
您需要通过转义字符来表示不允许作为JS字符串中的文字(如新行)的字符。由于JSON是一种基于JavaScript的文字语法主题的数据格式,因此您可以使用PHP的json_encode
函数将任何基本数据类型(字符串,数字,数组,关联数组)转换为带有所有正确转义字符的JavaScript代码。
默认情况下,它甚至可以转义/
,因此您可以安全输出字符串</script>
。
alert(<?=json_encode($str_alert);?>);
由于"
将被包含在JSON,你不应该手动添加。
它的工作原理,谢谢 –