开发者

Insert JavaScript data chunk (JSON) into an HTML page

I need to include a JavaScript object (JSON) in my HTML page.

JSON is rendered at the same time page HTML is rendered on server. Data is not retrieved using AJAX call. I can think of two ways of doing this, and looking for feedback and recommendations.

What are good practices for passing JavaScript (JSON) blob with a page?

Option 1

HTML:

<script type='text/javascript'>
    var model = { <JSON> };
</script>

.js:

function doSomething() { <use this.model here> }

Option 2

HTML:

<script type='text/javascript'>
    loadModel({<JSON>});
</script>

.js (included at the top of the html file):

var model = null;
function loadModel(model) { this.model = model; }
function doSomething() { <use this.model here> }

Variation Instead of including JSON in HTML, JSON can be stored in a separate .js file. Any comments on doing so?

Option 1 lets you include .js file anywhere, and including it at the bottom of the page makes it render faster (good thing), but since JavaScript renders the model on the page, this makes it a moot point. Still not depending on the location of the .js inclusion makes it less error prone.

Also R# complains (reasonably) about model being uninitialized.

Option 2 feels better (it encapsulate details better, f开发者_JS百科or one), but .js must be included before call to loadModel.

I have seen and done both ways, but didn't notice any significant advantages of one way over the other.

Server platform should be irrelevant, but it is IIS 7.5/ASP.NET MVC 3/Razor


Forget your two suggestions - both are extremely vulnerable to XSS. NEVER PUT UNTRUSTED TEXT IN A SCRIPT TAG.

Instead, use the owasp recommendation.

Stick your (HTML encoded) JSON in the DOM like so:

<div id="init_data" hidden>
    <%= html_escape(data.to_json) %>
</div>

Then read it in JavaScript like so:

// external js file
var dataElement = document.getElementById('init_data');
// decode and parse the content of the div
var initData = JSON.parse(dataElement.textContent);


There would be ever so slightly more overhead with option two. As you have the overhead of a function call, and an extra variable (your parameter), which will be allocated and deallocated.

As you said, there is little advantage/disadvantage to either way.


Can you use jQuery? Then you can use the DOM ready event instead of including javascript in your HTML.

EDIT:

Hmm, in that case you could include the JSON inside a hidden element when the page is generated. Then inside the DOM ready event you could read and parse it from the page using jQuery.

Another alternative might be to use HTML 5 data attributes and including the data in one of those.

If it were me I'd probably just use an ajax call since it is easier and seems a little cleaner.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜