Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
1
rated 0 times [  5] [ 4]  / answers: 1 / hits: 15219  / 13 Years ago, wed, june 29, 2011, 12:00:00

I know how to use $.each in my program which is written in Java
like this



$.each( ['a','b','c'], function(i, l){ 
alert( Index # + i + : + l );
});


what about If I want to pass arraylist or string array from my java program to the JQuery any one knows how??



I wrote



String[] arr1=new String[2];
arr1[1]=whatever;
arr1[2]=ksj;
$.each( arr1, function(i, l){
alert( Index # + i + : + l );
}


but it does not work?






Update:: I have jsp page which contains part of java as follows:



<%@page import=java.lang.reflect.Array%>
<%@page import=java.util.ArrayList%>
<%@page contentType=text/html pageEncoding=UTF-8%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=UTF-8>
<title>JSP Page</title>

<style>
.highlight { background-color: yellow }
</style>
</head>
<body>
<h1>Hello World!</h1>
<% ArrayList wordslist = new ArrayList();
wordslist.add(Hello);
wordslist.add(again);

String[] arr1=new String[wordslist.size()];
for (int i=0; i<wordslist.size();i++)
{
arr1[i]=wordslist.get(i).toString();
}%>



<a href=http://jquery.com/>jQuery</a>

<p> Hello again and again</p>
<script src=http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js></script>
<script src=jquery.highlight-3.js></script>
<script>

$(document).ready(function(){
alert( arr1 );
var arr=new Array();
arr.

$.each( arr, function(i, l){
alert( Index # + i + : + l );
}
)


});

</script>
</body>
</html>


The problem is wordslist arry is dynamic and I want to pass it to the JQuery ?? How can I do that without using inline embedded java please help Is there a way to pass wordslist to arr array in the Jquery!!!
This really make me disappointed!!


More From » jquery

 Answers
15

Use a JSON library for Java. Then serialize your ArrayList to JSON:



ArrayList wordslist = new ArrayList();
wordslist.add(Hello);
wordslist.add(again);

String json = (new JSONArray(wordslist)).toString();


Echo the JSON text at the appropriate place in your JavaScript code. E.g.



$(document).ready(function(){    
var arr = <%= json %>;
$.each( arr, function(i, l){
alert( Index # + i + : + l );
});
});


I'm actually not sure whether this is the right JSP syntax for printing a variable. Please correct if not.


[#91433] Tuesday, June 28, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dontaemauricioc

Total Points: 456
Total Questions: 84
Total Answers: 99

Location: Puerto Rico
Member since Fri, Oct 14, 2022
2 Years ago
;