vkosyj vkosyj - 5 days ago 5
Java Question

send data from java to javascript using jsp

Totally a newbie for jsp. In my project, I need to send an arraylist / array from java to javascript.

This is my java code in jsp.

<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<% List<String> strList = new ArrayList<String>();
strList.add("one");
strList.add("two");
strList.add("three"); %>


in my javaScript, I want something like below.

$(document).ready(function() {
var notes = ["one", "two", "three"];
});


So how do I send the data from java to javascript? Please be specific. Thank you in advance.




solution from Bilal

<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>

<html>
<body>

<% List<String> strList = new ArrayList<String>();
strList.add("one");
strList.add("two");
strList.add("three"); %>

<script type="text/javascript">

$(document).ready(function() {

var notes = new Array();
<%
for(String note:strList){
%>
notes.push('<%=note%>');
<%}%>
alert(notes[0]);
});
</script>


</body>



Answer

Try this one to use java code in javascript block. I use this code in a jsp page which print the values notes array one,two,three not sure if you are looking for the same thing or something else.

<% List<String> strList = new ArrayList<String>();
    strList.add("one");
    strList.add("two");
    strList.add("three"); %>

    <script type="text/javascript">

    $(document).ready(function() {

        var notes = new Array();
        <%
        for(String note:strList){
        %>
        notes.push('<%=note%>');
        <%}%>
        alert(notes);
    });
    </script>

this is my full jsp page code

<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script
  src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
</head>

<% List<String> strList = new ArrayList<String>();
strList.add("one");
strList.add("two");
strList.add("three"); %>

<script type="text/javascript">

$(document).ready(function() {
    var notes = new Array();
    <%
    for(String note:strList){
    %>
    notes.push('<%=note%>');
    <%}%>
    alert(notes);
});
</script>
<body>

</body>
</html>
Comments