0

How can I access a jsp array in javascript function with in a single jsp page?

String[] abc[]={"saab","volvo","bmw","Benz","Porsche","Jaguar"};
abc[0]="saab";
1
  • for (i=0;i<(document.getElementById("abc.length").value);i++) { alert("in loop"); var sar=request.getParameter("abc[i]"); var xyz = document.createElement("option"); xyz.text = abc[i]; xyz.value = abc[i]; abc.add(xyz); Commented Mar 20, 2013 at 12:22

3 Answers 3

0

print it to response literally and handle it via javascript.

behind-the-scene: jsp-inline code is running on the server side. javasrcript code runs on browser..

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

Comments

0

You should serialize it to json object first with for example FlexJson.

You could serialize java array to json array which should look like

[{item1, item2},{item},{item1,item2}]

with that method

String[] temp = ...
StringBuilder builder = new StringBuilder();
builder.append("[");
for(int i = 0 ; i < temp.length ; i++){
    builder.append(temp[i]);
    if(i != temp.length - 1 ){
    builder.append(",");
}
}
builder.append("]");
String jsonArray = builder.toString();

and add this to your request;

then in your javascript use

var array = <%= request.getAttribute("temp")%>;

check if this is it with

console.log(array);

1 Comment

please can u give me an example
-1
<%  
String[] abc={'saab',' volvo',"bmw","Benz","Porsche","Jaguar"};  
%> 

<script language="JavaScript">  

var jsArr = new Array();  
<%  
for (int i=0; i < abc.length; i++) {  
%>  
jsArr[<%= i %>] = '<%=abc[i] %>';   //Here is the latest update check it sravan .Put single quotes.
<%}%> 
</script>

  function myFunction()
  {
    var select = document.getElementById("dropDownId");

      for ( var i = 0; i < jsArr.length; i++ ){

      var option = document.createElement("option");
      // set the text that displays for the option
       option.innerHTML = status[i];
     // add the option to your select dropdown
       select.appendChild(option);

   }

1 Comment

give <select name="someName" id="demo"> in place of <select name id="demo">

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.