dongyanjing5975 2013-09-16 23:09
浏览 62
已采纳

打印出Javascript时包含换行符的PHP字符串causins问题

I have a PHP string that contains an address and as such contains a few lines. One example could be:

$custDetails = "
123 Main Street
City
Area Code
";

Although this address is retrieved using an SQL query, not declared in PHP.

I would like to replace the go to line characters by something else, temporarily, to make modifying this string easier in another javascript function. But I'm running in to some problems. This code:

echo "
<script>
  if ('$custDetails'.indexOf('
') != -1)
     alert('yes');
  alert('$custDetails');
</script>
";

Becomes:

<script>
  if ('123 Main Street
City
Area Code'.indexOf('
') != -1)
  alert('yes');
  alert('123 Main Street
City
Area Code');
</script>

after treated by PHP. The "go to lines" in the string are treated as go to line in the script tag, and as such messes up the script. Additionally, I can't detect the char because it is treated as a go to line, and messes up the script...

How can I make a string with multiple lines usable in javascript?

EDIT: As suggested in one of the answers, I tried replacing " " with 'n' in PHP before calling the javascript

$custDetailsBis = str_replace("
", '
', $custDetails);

echo "<script>
alert(\"$custDetailsBis\");
</script>";

I still doesn't work, output in browser:

<script>
  alert("16 St Andrews Street

Dundee

DD1 2EX");
</script>

Note that I know have that have appeared on the browser output, but there are still line breaks. Again the line breaks are causing errors in the javascript.

  • 写回答

4条回答 默认 最新

  • dongyi5570 2013-09-16 23:14
    关注

    Try this:

    $custDetailsEscaped = str_replace("
    ", '
    ', $custDetails);
    

    Note the double quotes for the first argument and single quotes for the second - it's significant here.

    Then replace all instances of $custDetails in your echo statement with $custDetailsEscaped:

    $custDetailsEscaped = str_replace("
    ", '
    ', $custDetails); 
    
    echo "
    <script>
      if ('$custDetailsEscaped'.indexOf('\\
    ') != -1)
         alert('yes');
      alert('$custDetailsEscaped');
    </script>
    ";
    

    Output:

    <script>
      if ('
    123 Main Street
    City
    Area Code
    '.indexOf('
    ') != -1)
         alert('yes');
      alert('
    123 Main Street
    City
    Area Code
    ');
    </script>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP