0

Is there a simply way to read bean values in a .js file?

I have an external JS file, arrays.js, which contains some arrays, used to populate a series of within a JSP page.

Now I need to fill the content of those arrays reading values.

I have to use the external js file, because it also contains lots of other methods to make the application work.

Thank you in advance

Pierpaolo
  • 567
  • 3
  • 7
  • 17

2 Answers2

0

In arrays.js file create a function function populateArray(arg1, arg2). Now you have a global function accessible from anywhere on your page, pass the values that you want to populate the arrays with as arguments to populateArray function and inside the function write the logic to populate your arrays.

Juzer Ali
  • 4,109
  • 3
  • 35
  • 62
0

Simplest way is to let JSP print it as a global JS variable so that it's visible to the scripts which execute after DOM ready. E.g.

<script>var bean = ${beanAsJson};</script>

where ${beanAsJson} prints the bean in JSON format. You could use among others Gson for this.

Another way is to let the JS code send an ajax request to a servlet which writes exactly that bean in JSON format to the response. E.g. with little help of jQuery:

$.getJSON('jsonServlet', function(bean) {
    // ...
});

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Unfortunately, I do not know how to write that kind servlet, so in the main JSP, which does the include of the .js file, I will do something like: var arr={msg1:, msg2:} so that I can access arr from arrays.js – Pierpaolo Feb 17 '12 at 09:14