JavaScript 中的 PHP 转义

问题描述 投票:0回答:1

我正在尝试从数据库查询中输出项目描述。

这是一段应该输出带有名称等描述的代码...

<?PHP

$type = "item";
$limit = 16;

$preparedStatement = $SQL->prepare('SELECT * FROM z_shop_offer WHERE offer_type = :type LIMIT :limit');

$preparedStatement->bindParam(':type', $type, PDO::PARAM_STR);
$preparedStatement->bindParam(':limit', $limit, PDO::PARAM_INT);
$preparedStatement->execute();

if ($preparedStatement->rowCount() > 0) {
        // Define how we want to fetch the results
        $preparedStatement->setFetchMode(PDO::FETCH_ASSOC);
        $iterator = new IteratorIterator($preparedStatement);

        foreach ($iterator as $item) {

        echo '
        <div class="ServiceID_Icon_Container" id="ServiceID_Icon_Container_'.$item['id'].'">

          <div class="ServiceID_Icon_Container_Background" id="" style="background-image:url('.$layout_name.'/images/serviceid_icon_normal.png);">

            <div class="ServiceID_Icon" id="ServiceID_Icon_'.$item['id'].'" style="background-image:url(' . $config['site']['item_images_url'] . $item['itemid1'] . $config['site']['item_images_extension'] . ');" onclick="ChangeService('.$item['id'].', 12);" onmouseover="MouseOverServiceID('.$item['id'].', 12);" onmouseout="MouseOutServiceID('.$item['id'].', 12);">

              <div class="PermanentDeactivated">
                <span class="HelperDivIndicator" onmouseover="ActivateHelperDiv($(this), \''.$item['offer_name'].'\', \''.htmlentities($item['offer_description']).'<BR><BR>\', \'\');" onmouseout="$(\'#HelperDivContainer\').hide();">
                  <div class="ServiceID_HelperDiv"></div>
                </span>
              </div>

            </div>
          </div>
        </div>
        ';

        }
}
?>

我已经尝试过

htmlentities
htmlspecialchars
addslashes

这是存储在数据库中的描述(在这个数据库中,它停止显示带有描述的工具提示。

激活一小时 1.5 倍经验。它只有一项费用。 当一个注入处于活动状态时使用任何其他注入只会叠加它的 时间而不是经验。如果您注销或,时间不会停止 死吧。

如何正确转义/输出描述?

javascript php mysql pdo
1个回答
1
投票

您可能遇到的问题是您需要双重转义数据。你需要:

  • 首先将其转义为 HTML
  • 第二个是 JavaScript。

所以除了

json_encode()
之外还需要使用
htmlspecialchars

 onmouseover="'.htmlspecialchars(
     'ActivateHelperDiv($(this), '.json_encode($item['offer_name']).')'
 ).'">'

在这里,您对整个属性值使用 htmlspecialchars,对从 PHP 传递到 JavaScript 的值使用 json_encode

© www.soinside.com 2019 - 2024. All rights reserved.