将HTML放入JSON中 [英] Putting HTML in JSON

查看:598
本文介绍了将HTML放入JSON中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据标题,将HTML放入JSON中被认为是一种很好的做法吗?我需要这样做的原因是因为我希望有一个自定义下拉列表,其中列表来自用户输入,而json看起来像这样:



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

并且我有以下foreach(请记住,这是我的代码的精简版本,验证已就位,但为了方便起见这个问题我拿出来了)

  $ list = / **代码从mysql中获取'Tasks'列表及其标题** /; 
$ title ='任务';
$ listHtml ='';
foreach($ list为$ content){$ listHtml。='< li>'。 htmlspecialchars($ content,ENT_QUOTES,'UTF-8')。 < /立GT;; }

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

我担心的是可能会有一些特殊字符可能会破坏JSON字符串。请帮助。

解决方案

您不会是第一个这样做的人,当然也不是最后一个。 b
$ b

为了真正回答这个问题,假设你遵循协议/标准并且不打破它(例如包括字符串中的引号而不逃避它们),你应该没问题。 json_encode在所有这些方面都做得很好,但是作为@Kolink提到的确保你先将它编码为UTF8,否则Unicode编码字符偶尔会破坏它,导致输出空。



除此之外,程序员偏好使用它。有些人会避免它,并保持UI在页面上的工作,其他人有服务器生成的UI,让JavaScript只是转储它 - 无论是这种方式是你的电话,并完全可以接受。


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.

解决方案

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.

这篇关于将HTML放入JSON中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆