我需要把一个JSON对象放到HTML元素的属性中。
> HTML不需要验证。
Quentin回答:Store the JSON in a data-* attribute,这是有效的HTML5。
> JSON对象可以是任何大小 – 即巨大
Quentin回答:根据常规约定,将JSON字符串编码到属性之前。 For PHP, use the htmlentities()函数。
EDIT – 使用PHP和jQuery的示例解决方案
将JSON写入HTML属性:
$data = array(
'1' => 'test',
'foo' => ''
);
$json = json_encode($data);
?>
使用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);
});