html_entity_decode()不处理存储在html data- *属性中的数据

时间:2017-07-17 07:38:22

标签: php jquery html5 twitter-bootstrap

我正在通过htmlentities()检索从数据库编码的数据,通过html_entity_decode()解码并在html页面上显示它们。如果我回显页面上的解码数据,它会正确显示。但是,如果我将解码数据传递给data- *属性并通过jQuery检索它,则显示的(已解码的)数据具有html标记。我在这里强调了我的代码的重要步骤:

// data retrieved from my WYSIWYG text editor
$content = "Which one of the following statements is true about the number of faces and edges<div>of a square based pyramid?</div>";

// encode form content and store in the database
$encodedcontent = htmlentities($content, ENT_QUOTES, 'UTF-8', false);

/** The way data is stored in db: Which one of the following statements is true about the number of faces and edges&lt;div&gt;of a square based pyramid?&lt;/div&gt; **/

// retrieve the same content from the database and decode it
$contentFromDb = html_entity_decode($encodedcontentfromdb);

// now display $contentFromDb in html

// first output displays correctly as expected
<div><?php echo $contentFromDb; ?></div>

将php变量存储在data- *属性中以在jQuery中检索

<div id="modalcontentlink" style="display:none" data-dbcontent="<?php echo $contentFromDb; ?>"></div>

使用jQuery检索data-dbcontent属性值

$(document).ready(function() {
    $("#modalcontentlink").click(function(){

        var dbContent = $(this).data('dbcontent');
        // display in bootstrap modal

        $("#modal-dbcontent").text($dbContent); // #modal-dbcontent represents id of the div element in which am displaying the content

  });
});

第二个输出是:

Which one of the following statements is true about the number of faces and edges<div>of a square based pyramid?</div>

有人请说明为什么第二个输出仍然有html标签? 非常感激。 因此经过一些研究,我了解到jQuery为您提供了作为字符串输入的内容,因此在输出中显示了html标记。我跟着this suggestion

$(document).ready(function() {
    $("#modalcontentlink").click(function(){

        var dbContent = $(this).data('dbcontent');
        // display in bootstrap modal
        $result = $('<div/>').html(dbContent).text();

        $("#modal-dbcontent").text($dbContent); // #modal-dbcontent represents id of the div element in which am displaying the content

  });
});

0 个答案:

没有答案