dream1849 2013-07-23 15:44
浏览 29
已采纳

使用PHP插入JavaScript时获得意外的换行符

I am trying to insert items into a javascript array for the autocomplete function. I take the values that I need for the array from a database, so I grab them with PHP. Then I just push each item into the javascript array. However, it keeps telling me that I have an "unexpected token ILLEGAL" and it looks like it's pointing at the single "quote" character that gets inserted, then has a newline, then continues to the actual value.

My javascript/PHP

<script type="text/javascript">
        $(function() {
           var availableTags = [];
           <?php

              foreach ($modelList as &$model)
                 echo "availableTags.push('$model');" . "
";
           ?>
           $("#devicemod").autocomplete({
                 source: availableTags
           });
        });


        </script>

Then the error message...

$(function() {
               var availableTags = [];
               availableTags.push('
***Uncaught SyntaxError: Unexpected token ILLEGAL***
ODEL: T]422P');availableTags.push('');availableTags.push('!');availableTags.push('!6.1/120{ MODEL: TM402P');availableTags.push('!A`$');availableTags.push('!DP1110   CREATED ON: JAN 29 2002');availableTags.push('!MODEL: TM402P');

It should turn out to be...

availableTags.push('ODEL:T]422P');
availableTags.push('');
etc...
  • 写回答

2条回答 默认 最新

  • dongse5408 2013-07-23 15:56
    关注

    Using json_encode() you can do this in a single (and safe) step:

    <script type="text/javascript">
    $(function() {
       $("#devicemod").autocomplete({
           source: <?php echo json_encode($modelList); ?>
       });
    });
    </script>
    

    The json_encode() function makes sure that the values are properly escaped according to the rules of JavaScript notation. This prevents nasty surprises when the values contain single quotes in this case.

    If $modelList is not a true list (i.e. the keys are not numbered sequentially), you should apply array_values() first:

    ...
           source: <?php echo json_encode(array_values($modelList)); ?>
    ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行