开发者

How to show html tags converted by PHP's htmlentities into div using jQuery?

I have a dynamic string from PHP that I encoded using htmlentities() so I can pass it on AJAX using jQuery and JSON. Now I got something like

{ "error": "false", "html": "<div id="user_add_title">Adding New User<div class="showhide-div"><a class="hideShowToggle" href="#" onclick="$('#account_title').show();$('#account').show();$('#users_container').html('')">[cancel]</a></div></div>" }

and when I want to show it in an AJAX success callback function like:

success: function(json) {
    if(json.error == 'false')
        $("#users_container").html(json.html);
    else
        showMsg(json.msg);
}

what's displayed in the is the entities开发者_开发知识库 itself

<div id="user_add_title">Adding New User<div class="showhide-div"><a class="hideShowToggle" href="#" onclick="$('#account_title').show();$('#account').show();$('#users_container').html('')">[cancel]</a></div></div>

instead of being rendered by the browser.

If I use html or text as dataType in my jQuery AJAX call, the tags are rendered properly. I want to use JSON because I need to catch if the process has an error or not.


You don't need to encode your own markup with htmlentities when passing it to jQuery. Simply remove the call to htmlentites() and send your marked up HTML.

The exception is, if some part of the code contains text supplied from the user. In this case, you must htmlencode() that text, and leave it encoded even when it's appended to a DOM element for display.


I have solved it! Instead of using PHP's htmlentities() which converts greater than and less than signs as well as the quotes, I just used addslashes() to only convert (or add backslashes) characters that need backslashing such as the quotes.

I figured out that the quotes were the ones causing the json not being parsed correctly, the reason why I used htmlentities in the first place, thinking that converting everything would solve it. Thanks for your valuable input.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜