【问题标题】:double qoutes in variables causing javascript error使用javascript错误的变量中的双引号
【发布时间】:2009-10-29 09:32:13
【问题描述】:

在我下面的代码中,当 $artist 或 $title 变量包含 " 时,它会导致 JavaScript 命令中断。

除了addslashes() 之外,我还有其他方法可以对这些进行编码来解决这个问题吗?

$artist = addslashes($row['artist']);
    $title = addslashes($row['title']);

    echo '<div class="play" style="display: inline"><a href="javascript:playSong'."('$artist','$title','$row[file]','$row[id]')".'">

【问题讨论】:

    标签: php javascript


    【解决方案1】:

    您可以考虑对变量进行 url 编码,例如

    $artist = rawurlencode($row['artist']);
    $title = rawurlencode($row['title']);
    
    echo "..... playSong(unescape('$artist'), unescape('$title')... ";
    

    或将解码移到 playSong 函数中。

    // 编辑:这就是你正确引用的方法

    echo "<div class='play' style='display: inline'><a href=\"javascript:playSong(unescape('$artist'),unescape('$title'),'$row[file]','$row[id]')\">....";
    

    【讨论】:

    • 问题是,如果在 echo '' 中有“;它会破坏 JavaScript 命令而不是显示错误。所以我猜我需要正确封装变量。
    【解决方案2】:

    你可以试试urlencode()。

    【讨论】:

      【解决方案3】:

      试试这个

      echo '<div class="play" style="display: inline"> <a href="javascript:playSong('$artist','$title','$row[file]','$row[id]')" >'

      【讨论】:

      • 我格式化了你的代码,因为标签被去掉了。 echo ' ' 让我哈哈大笑
      猜你喜欢
      • 2012-07-28
      • 2016-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-25
      • 1970-01-01
      • 2012-05-17
      相关资源
      最近更新 更多