J'ai besoin de mettre un objet JSON dans un attribut sur un élément HTML.
Le HTML n'a pas à valider.Réponse de Quentin: Stockez le JSON dans un
data-*
attribut , qui est HTML5 valide.L'objet JSON peut être de n'importe quelle taille - c'est-à-dire énorme
Réponse de Maiku Mori: La limite pour un attribut HTML est potentiellement de 65 536 caractères .
Et si le JSON contient des caractères spéciaux? par exemple
{foo: '<"bar/>'}
Réponse de Quentin: Encodez la chaîne JSON avant de la mettre dans l'attribut, selon les conventions habituelles. Pour PHP, utilisez la fonction .
htmlentities()
EDIT - Exemple de solution utilisant PHP et jQuery
Écriture du JSON dans l'attribut 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>
Récupération du JSON à l'aide de jQuery:
$('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-json
vous devez utiliser $(this).data('json')
, le jQuery vous a couvert sur cette partie.