0

Is this possible? I am using javascript, AJAX and JSON to pull data from a Java servlet and i'd like to display elements of the javascript array I create within my HTML (as opposed to creating large chunks of HTML within javascript). I know I can muck up my html using:

<script>document.write(arrayVar[0].firstName);</script>

But i'd really like to avoid that. In the past I would use JSTL and EL tags when pulling data from the server, but is there a similar way to do this purely with javascript? I wouldn't be opposed to using an external library - I just don't know of any because I don't have a ton of experience with JS.

3 Answers 3

1

You could use any javascript templating library like http://mustache.github.com/ or ones that come with underscore.js ( or jquery templates (although I understand that these are deprecated now). Javascript templates are probably as magical as you will get for this.

Sign up to request clarification or add additional context in comments.

1 Comment

jQuery templates weren't deprecated per-se, they were left as a separate library.
0

I do try to avoid document.write wherever possible as it can mess up pages when this call is returned in HTML through AJAX.

Unfortunately, to answer your question, probably not - at least not in a way better than you're currently doing. document.write can be avoided by instead using the DOM methods, such as:

document.getElementById('test').innerHTML = arrayVar[0].firstName;

With pure JavaScript, I don't see any other way of doing this that would be similar to EL syntax.

1 Comment

I sort of figured the same. I was hoping there might be some magical library our there or best case scenario: a way to do this purely in JS that I never knew about.
0

Saxon-CE (currently an Alpha release) is an XSLT 2 processor with extensions for browser interaction - it's implemented in JavaScript and deployed in the same way as a JS library.

With this, you could write a template to iterate the JavaScript array (by calling a JS function) and insert each value into an HTML literal-result element within the template. The resulting HTML can then be appended to, or replace, any part of the HTML DOM.

The template can either run on page load, or be linked to any DOM event.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.