无法在JavaScript警告框中添加新行?

Rol*_*and 1 javascript php

我在PHP中生成一个字符串,然后最终将此字符串传递到Javascript警告框中,我的问题是我实际上无法在警报框中添加换行符.

我的代码如下所示

$str = "This is a string\n";
$alert = $str."This is the second line"; 

     if(!empty($alert)){
                    ?>
                        <script type="text/javascript">
                            $(document).ready(function() {
                                alert('<?=$alert?>');
                            });
                        </script>
                    <?php
                }
Run Code Online (Sandbox Code Playgroud)

我收到了错误

未确定的字符串文字

如果我从字符串中删除\n,它可以100%工作,但没有换行符

Pek*_*ica 19

这是因为PHP在JavaScript有机会之前解释了\n,导致Javascript代码中出现真正的换行符.尝试

\\n
Run Code Online (Sandbox Code Playgroud)