【发布时间】:2011-11-11 11:14:46
【问题描述】:
我需要将 JSON 对象放入 HTML 元素的属性中。
-
HTML 不必验证。Quentin 回答:Store the JSON in a
data-*attribute,这是有效的 HTML5。 -
JSON 对象可以是任意大小 - 即巨大
由 Maiku Mori 回答:The limit for an HTML attribute is potentially 65536 characters。
-
如果 JSON 包含特殊字符怎么办?例如
{foo: '<"bar/>'}Quentin 回答:按照通常的约定,在将 JSON 字符串放入属性之前对其进行编码。 For PHP, use the
htmlentities()函数。
编辑 - 使用 PHP 和 jQuery 的示例解决方案
将 JSON 写入 HTML 属性:
<?php
$data = array(
'1' => 'test',
'foo' => '<"bar/>'
);
$json = json_encode($data);
?>
<a href="#" data-json="<?php echo htmlentities($json, ENT_QUOTES, 'UTF-8'); ?>">CLICK ME</a>
使用 jQuery 检索 JSON:
$('a').click(function() {
// Read the contents of the attribute (returns a string)
var data = $(this).data('json');
// Parse the string back into a proper JSON object
var json = $.parseJSON($(this).data('json'));
// Object now available
console.log(json.foo);
});
【问题讨论】:
-
您应该解释原因并要求不同的解决方案,因为我很确定这不是最好的。您可以使用 data-something 属性,但我不确定它们是否可以容纳“大量”文本。至于特殊字符,您可以对文本进行编码(escape() 和 unescape())。
-
是的,限制为 65536 个字符 (stackoverflow.com/questions/2752457/…)
-
顺便说一句,如果你的属性名为
data-json,你应该使用$(this).data('json'),jQuery 已经涵盖了这部分。 -
请注意,不需要将数据后缀命名为 json。如果您将有效的 json 放在任何 data-custom_attribute 中,它将与 jQuery 一起正常工作。
-
请修正大括号序列 )}; => });
标签: javascript php html json