newbie
newbie

Reputation: 75

Passing database values from jsp to javascript

How do I pass all the values from a database table to javascript. I tried using this but only one value is passed in the javascript.

This is the code in my jsp

while(rs.next){
String timestamp= new SimpleDateFormat("MM/dd/yyyy hh:mm a").format(rs.getTimestamp("enddate"));
}

and this is how it receives in my javascript

<script language="JavaScript">

TargetDate = "<%=timestamp%>";

Everytime i run the script only the first value from the table is passed in the javascript. How can I fix this?

Upvotes: 2

Views: 1616

Answers (2)

spiderman
spiderman

Reputation: 11112

Basically you need to iterate over your result set and get the list of timetstamp. Currently you are fetching only one timetstamp and displaying it.

Then you need to convert this Java list to Javacript array Convert the Java ArrayList to JSON String, and use JSON.parse() to get Javascript object

Once you have the Javascript object, you are there..

json in java : http://json.org/java/

Alternate approach:

Note: Usage of scriptlets in JSP is NOT at all recommeded. Try using JSTL tag library.

Since you are looking for this, here it is

    <%
        int length = 3; // in your case, resultset count
        String results[] = new String[length];
        results[0] = "result1";
        results[1] = "result2";
        results[2] = "result3";

        // convert java string array to a javascript array

        StringBuffer sb = new StringBuffer();
        sb.append("[");
        for (int i = 0; i < results.length; i++) {
            sb.append("\"").append(results[i]).append("\"");
            if (i + 1 < results.length) {
                sb.append(",");
            }
        }
        sb.append("]");
        String jsarrayAsJavaString = sb.toString();
    %>
    <script language="JavaScript">
     var target = <%= jsarrayAsJavaString %>
     alert(target[0]); // target is a javascript array object. That's why you can do this
     alert(target); // print the entire javascript array

     //looping JS array
     for(var i=0;i<target.length;i++) {
         alert(target[i]); 
     }
    </script>

</body>

Upvotes: 2

cenk ebret
cenk ebret

Reputation: 697

The problem i see in your code is, if i dont misunderstand; you try to take all timestamps from rs. But you declare one timestamp.

So i think, you should loop in rs, and declare timestamp in it and for all your rows, you should push it into an array on java side.

Then, you should return it as a timestamp json array as you try to do it in your javasript side. So for javascript, you will have a string array. There, you should loop again i think.

Upvotes: 0

Related Questions