Skip to content Skip to sidebar Skip to footer

Passing An Array From Java (jsp) To Jquery

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

Solution 1:

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

ArrayList wordslist = newArrayList();
wordslist.add("Hello");
wordslist.add("again");

String json = (newJSONArray(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.

Solution 2:

Well your code is formatted wrong, for starters. You're missing the closing bit. Second, indexes are zero-based. Third, you created the array wrong.

var arr1 = newArray();
arr1[0]="whatever";
arr1[1]="ksj";
$.each( arr1, function(i, l){ 
   alert( "Index #" + i + ": " + l );
}); //Missed the );

Overall, I recommend writing JavaScript rather than Java when using jQuery. Just a tip. :)

Solution 3:

Javascript variables are not declared with a type, and you cannot ask for an array of String, because Javascript only has one kind of array, which holds anything. Also, make sure your brackets balance. Finally, array indices in Javascript start at 0, just like in most other programming languages (including Java, which you seem to be getting confused with - but Java and Javascript have nothing to do with each other, despite the names).

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

Post a Comment for "Passing An Array From Java (jsp) To Jquery"