简体   繁体   中英

Can't add new lines in JavaScript alert Box?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM