Search code examples
javajavascriptajaxjspscriptlet

Passing server side data to JavaScript - Scriplet or AJAX call - which is better?


In a property file at server side I'm maintaining a comma separated list of words.

words.for.js=some,comma,separated,words

I want to create a JavaScript array out of these words.

var words = [some,comma,separated,words];

I thought of two options

1.Using a JSP scriplet, create a global variable

<%  
    out.print("<script> var words = [");
    out.print( PropertyLoader.getAsCommaSeparated("words.for.js") );
    out.print(" ] </script>");
%>

2.Expose a service/ action (i.e. /getWords.do ) and call this using AJAX and construct the array.

I'm not sure which is better of the two and appreciate your thoughts here. Or is there any better way to do this?

Thanks.

EDIT:

This is also a comparison of global JS variable (in case of option 1) vs additional http request (in case of option 2) - which one is worse. I would like to know your thoughts from this perspective as well.


Solution

  • I prefer embedding the server-side data within your JSP's markup - #1. It is faster and doesn't require a callback.

    For me, it is all about the nature of the data. In your case, the data in that properties file seems unlikely to change without a server reboot. So, saving an additional network callback and embedding it into the markup feels appropriate for a global variable.

    If you were dealing with some sort of dynamic data, an ajax callback onload would be better.