Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/387.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在不中断javascript代码的情况下使用javascript字符串进行换行?_Javascript_Php - Fatal编程技术网

如何在不中断javascript代码的情况下使用javascript字符串进行换行?

如何在不中断javascript代码的情况下使用javascript字符串进行换行?,javascript,php,Javascript,Php,我需要在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)){ ?>

我需要在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>

$(文档).ready(函数(){
警报(“”);
});
它会破坏javascript代码并显示错误

SyntaxError:未终止的字符串文字


请给我任何解决方案

如果没有转义(),Javascript字符串不能跨越换行符。有关详细答案,请参见此问题:


添加
\
以在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>

$(文档).ready(函数(){
警报(“”);
});

您需要通过转义字符来表示JS字符串(如新行)中不允许作为文本的字符

由于JSON是一种基于JavaScript文本语法主题的数据格式,因此可以使用PHP的
JSON_encode
函数将任何基本数据类型(字符串、数字、数组、关联数组)转换为具有所有正确转义字符的JavaScript代码

默认情况下,它甚至会转义
/
,因此您可以安全地输出字符串

alert();
由于JSON中将包含
,因此不应手动添加它们

alert(<?=json_encode($str_alert);?>);