最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Can't add new lines in JavaScript alert Box? - Stack Overflow

programmeradmin2浏览0评论

I'm generating a string in PHP and then eventually passing this string into a JavaScript alert box, my problem is I actually can't add line breaks in my alert box.

My code looks as follows

$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
}

I'm getting the error:

Undeterminnated string literal

If I remove the \n from the string it works 100% but without line breaks.

I'm generating a string in PHP and then eventually passing this string into a JavaScript alert box, my problem is I actually can't add line breaks in my alert box.

My code looks as follows

$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
}

I'm getting the error:

Undeterminnated string literal

If I remove the \n from the string it works 100% but without line breaks.

Share Improve this question edited Oct 26, 2020 at 10:42 Alex 1,5801 gold badge15 silver badges27 bronze badges asked Nov 17, 2009 at 12:17 ElitmiarElitmiar 36.8k77 gold badges182 silver badges233 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 19

This happens because PHP interprets the \n before JavaScript has the chance to, resulting in a real line break inside the Javascript code. Try

\\n

You need to change $str to

$str = "This is a string\\n";

so that the \n gets passed to the JavaScript.

发布评论

评论列表(0)

  1. 暂无评论