I would like to embed JSON in HTML. The most elegant solution I have found makes use of the script
-tag and the mime media type application/json
.
I am answering my own question since I have had to find a solution. My solution is based on what Bergi suggested using inline JSONP. It is a better solution than finding an answer to my actual question since no manual JSON-parsing is required.
The JSON-data (and HTML) is generated with Java Server Pages (JSP).
Step 1
A custom variable name is created using JSP. It will be used as the javascript global variable to which the json data will be assigned to. The name is randomly generated to prevent naming conflicts on the same page.
jsnpData<%= java.lang.Math.round(java.lang.Math.random() * 1000000) %>
Step 2
The script tag has a cssClassname to identify it by and a data-var
-attribute, so that the custom variable name can be determined. ${ctrl.json}
is JSP and prints out JSON. Unlike JSONP which uses a callback-Function, a global variable is used. So far I have not experienced any drawbacks.
Step 3 Accessing the data (using jQuery) is as easy as:
var data = window[$('script.data').data('var')];
Example with context
HTML
jsnpData<%= java.lang.Math.round(java.lang.Math.random() * 1000000) %>
Javascript
$('button.fetchData', '.myWidget').click(function (e) {
var data = window[$('script.data', '.myWidget').data('var')];
});
I'm using inline JSONP to load JSON-data which is required on page load. It isn't a lot of data and it's one HTTP-Request less.