Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

As per title, is it considered a good practice to put HTML in JSON? The reason I need to do this is because I would like to have a custom dropdown where the list is coming from the user input, and the json looks like so:

{ listTitle: 'Tasks', listHtml: '<ul><li></li>...</ul>' }

and I have the foreach as following (keep in mind this is a stripped down version of my code, validation is in place, but for the sake of this question I took them out)

$list = /** Code to grab 'Tasks' list and its title from mysql **/;
$title = 'Tasks';
$listHtml = '';
foreach($list as $content) { $listHtml .= '<li>' . htmlspecialchars($content, ENT_QUOTES, 'UTF-8') . '</li>'; }

exit(json_encode(array(
   'title' => $title, 'listHtml' => '<ul>' . $listHtml . '</ul>'
)));

My worry is that there might be some special characters that might break the JSON String. Please help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
511 views
Welcome To Ask or Share your Answers For Others

1 Answer

You wouldn't be the first to do it, and certainly not the last.

To really answer the question, assuming you're following the protocol/standard and not breaking it (including quotes in the string without escaping them, for instance) you should be fine. json_encode does a great job at all this, but as @Kolink mentioned make sure you encode it to UTF8 first otherwise stray Unicode characters will occasionally break it resulting in empty output.

Beyond that, it's programmer preference to use it. Some avoid it and keep the UI work on the page, others have the server generate the UI and let JavaScript just dump it--either way it's your call, and perfectly acceptable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...