2

I need JavaScript array/multidimensional which is returned by Java class,

<script type="text/javascript">
     var strComboValue  = <%=DBComboOptions.getOptions(combos)%>;
</script>

Here, strComboValue is a JavaScript variable and the DBComboOptions.getOptions(combos) returns array in Java class. Now I want that array in JavaScript.

5
  • I don't know jsp but it seems that you've got the array in strComboValue Commented May 28, 2012 at 7:41
  • 2
    Use some json encoding library and call json encode on DBComboOptions.getOptions(combos) Commented May 28, 2012 at 7:42
  • @Esailija : this should be an answer. Commented May 28, 2012 at 7:43
  • possible duplicate of Populating JavaScript Array from JSP List Commented May 28, 2012 at 7:44
  • @JBNizet I'll rather close as duplicate :P Commented May 28, 2012 at 7:45

2 Answers 2

2

Just let Java/JSP print a syntactically valid JS array syntax. Keep in mind that Java/JSP and JavaScript doesn't run in sync. Java/JSP produces HTML as one large String and JS is just part of it. JS ultimately runs in the webbrowser once it has retrieved all that HTML output from Java/JSP.

Assuming that you ultimately want the following valid JS array syntax:

<script type="text/javascript">
    var strComboValue = [ "one", "two", "three" ];
</script>

Then you should write your Java/JSP code accordingly so that it prints exactly that syntax:

<script type="text/javascript">
    var strComboValue = [ 
<% 
    String[] options = DBComboOptions.getOptions(combos);
    for (int i = 0; i < options.length; i++) {
%>
        "<%= options[i] %>"
<%
        if (i + 1 < options.length) {
%>
            ,
<%
        }
    }
%>
    ];
</script>

It's only terribly unreadable (and not only because of using old fashioned scriptlets instead of taglibs). Easier, however, is to grab a JSON (JavaScript Object Notation) library like Google Gson and create an additional method getOptionsAsJson() which does something like the following:

public getOptionsAsJson(Object value) {
    return new Gson().toJson(getOptions(value));
}

And finally use it instead:

<script type="text/javascript">
    var strComboValue = <%=DBComboOptions.getOptionsAsJson(combos)%>;
</script>
Sign up to request clarification or add additional context in comments.

Comments

0

your can use json lib, on http://json.org there are many json librarys, i.e.

int[] arr = new int [] {1,2,3}; // java

convert to:

var arr = [1,2,3];  // javascript

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.