简体   繁体   中英

How can I add java array elements into java script array?

How can I add my java array contents into empty javascript array? I tried but its not working.

Here is my code in file.jsp.

<%@page import="javax.portlet.PortletPreferences" %>

   PortletPreferences prefs = renderRequest.getPreferences(); // here i am reading values from preferences in Liferay and rendering values

 <select id="dropdown1" onchange="changeAction(this.value);">
                        <option value="" selected="selected" >Select</option>
                        <option value="">value1</option>
                        <option value="">value2</option>
  </select>

      <label>Device</label>
      <%

       String device1 = prefs.getValue("device1","");
       String[] array1 = device1.split("\n"); // String[] array=["books","pens","cars"];
     %>

      <select id="dropdown2">
                <option value="select" selected="selected">Select</option>
      </select>

below is my Java script code, both jsp code and javascripts are inside same jsp file.

<script>
     function changeAction(optionVal){
     var tempArrayLabel = [];

     jQuery("#dropdown2").empty().append('<option value="-1" >Select</option>');

    if(optionVal == "selected val in first drop down") {

tempArrayLabel = "add values from array1 or device1"; // update the drop down list


}

for (var i=0;i<tempArrayLabel.length;i++){
    jQuery('<option/>').html(tempArrayLabel[i]).appendTo('#dropdown2');
}

}

 </script>

Thanks for any kind of suggestion.

Update

Try this (Java 8, see here for more ways to join an array in java )

<%  
  String[] array=["books","pens","cars"];
  String array_joined = '["' + String.join('","', array) + '"];';
%>

or use this instead to join the array in case the String.join menthod is not available

<%  
  String[] array=["books","pens","cars"];
  String array_joined = '"' + array[0] + '"';
  for (int i=1; i<array.length; i++) array_joined += ',' + '"' + array[i] + '"';
  array_joined = '[' + array_joined + '];';
%>

<script>
     var javaArray= <%= array_joined %> // renders ["books","pens","cars"];

     var tempArrayValue = [];

     function myFunction(){

     for(var i=0,j=0;i<javaArray.length;i++,j++){

     tempArrayValue[j]=javaArray[i]; //trying to store ["books","pens","cars"] values into "tempArrayValue"

     }

  }

</script>

Note i dont remember the jsp tags, so i may have used incorrect tags to render a jsp expresion above, use accordingly

found use <%= %> expression tag

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM