【问题标题】:php echo alert message with new line '\n' not working带有新行'\ n'的php echo警报消息不起作用
【发布时间】:2015-04-23 08:17:17
【问题描述】:

我想使用 alert() 显示一条消息

$message = "No result found for the following info:Name: ".$FullName."IC: ".$ID." in database.";
echo "<script>alert('".$message."'); window.history.back();</script>";

这是可行的,但如果我在消息中添加新行 '\n'

$message = "No result found for the following info:\nName: ".$FullName."\nIC: ".$ID." in database.";


它不会显示弹出消息。有什么问题?

【问题讨论】:

标签: javascript php string


【解决方案1】:

编辑它以不在 PHP 中更改为换行符,而是在 javascript 中:

'No result found for the following info:\nName: '.$FullName.'\nIC: '.$ID.' in database.'
^                                               ^           ^      ^     ^             ^

OR 通过添加额外的反斜杠:"\\n"

根据 Panther 的说法,也是事实:使用 'alert("' . $message . '")'

【讨论】:

    【解决方案2】:

    在换行符上添加另一个 \ 反斜杠:

    $message = "No result found for the following info:\\nName: ".$FullName."\\nIC: ".$ID." in database.";
    

    Output

    【讨论】:

      【解决方案3】:

      或使用 PHP_EOL

       $msg = 'Hello' . PHP_EOL . 'Next line';
      

      【讨论】:

      • 很好的答案
      【解决方案4】:

      \n 等不解释为单引号,而是双引号。

      echo "<script>alert(\"" . $message . "\"); window.history.back();</script>";
      

      echo '<script>alert("' . $message . '"); window.history.back();</script>';
      

      【讨论】:

      • 这不会影响$message中的内容
      • @GeraldSchneider:当你对某事投反对票时,你应该确定它不是解决方案。您在否决之前尝试过吗?当然可以,这就是 JS 解释转义字符如\n, \r, \t 等的方式。
      • 事实上我确实尝试过。如果您将其应用于$message 的定义,您的建议将起作用,就像 yergo 在他的回答中所做的那样。但是这种方式 $message 会被口头回应,包括破坏 javascript 代码的换行符。
      • @GeraldSchneider:如果在从 PHP 生成的 HTML 中,将是 alert("whatever \n content..."),在警报中将是两行。警报中的文本是否来自 PHP 无关紧要。
      【解决方案5】:

      你需要使用Line feed + Newline

      \r\n
      

      这将如以下脚本所示工作:

      echo "If you view the source of output frame \r\n you will find a newline in this string.";
      echo nl2br("You will find the \n newlines in this string \r\n on the browser window.");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-10-24
        • 1970-01-01
        • 2013-07-18
        • 2014-01-17
        • 1970-01-01
        • 2012-05-07
        • 2012-09-06
        相关资源
        最近更新 更多