I need to put a JSON object into an attribute on an HTML element.
The HTML does not have to validate.
Answered by Quenti
Another way you can do it – is put json data inside tag, but not with
type="text/javascript"
, but with type="text/bootstrap"
or type="text/json"
type, to avoid javascript execution.
Then, in some place of your program, you can ask for it in this way:
function getData(key) {
try {
return JSON.parse($('script[type="text/json"]#' + key).text());
} catch (err) { // if we have not valid json or dont have it
return null;
}
}
On server side, you can do something like this (this example with php and twig):