2

I am returning SQL Query result as a JSONArray to a JSP page. Now i want to show the data. I have written a code but it is working fine only for 23 objects in the JSONArray if JSONArray contains more the 23 object eval or JSON.parse function doesn't work. Please let me know how to solve this problem.

Below is the JS code i have written to iterate over this JSONArray.

var data = '<%=(JSONArray) request.getAttribute("resultArray")%>';
data = eval("(" + data + ")");
$(document).ready(function() {
   var table = $('<table/>').appendTo($('#column'));

   var rows = $('<tr/>').appendTo(table);
    $.each(data, function(rowid, row) {
       var rows = $('<tr/>').appendTo(table);
       $.each(row, function(column, data) {
           ($('<td/>').text(data)).appendTo(rows);
       })}); 
});
sharad-garg
  • 359
  • 1
  • 6
  • 12
  • 1
    Don't use **eval**, it's insecure, and JSON.parse should work properly, but you don't need to use it, simply don't output your data into string ;) http://www.json.org/js.html – Marek Sebera Aug 30 '12 at 16:39
  • What does `data.length` give you? – David Hellsing Aug 30 '12 at 16:41
  • 1
    Did you verify that you are getting valid JSON? http://jsonlint.com/ – gpojd Aug 30 '12 at 16:43
  • Thanks to all for the immediate reply. Marek, Please let me know then how to pass JSONArray object to Java Script. David, data.length just gives number of char's present in the String. gpojd, yes i am getting proper json object. Above code is working fine if JSONArray have less then 23 objects. – sharad-garg Aug 30 '12 at 16:52

1 Answers1

3

Just don't let JSP print it as a JS string syntax within quotes (which obviously needs to be parsed in order to get a JS object). Get rid of those quotes. JSON is already in proper JS object syntax. That's also all what "JSON" stands for.

var data = <%=request.getAttribute("resultArray")%>;
$(document).ready(function() {
    // ...
});

By the way, using scriptlets in JSP is a poor practice. If you're on JSP 2.0 already (which is out for almost a decade already), just use EL.

var data = ${resultArray};
$(document).ready(function() {
    // ...
});

Note, also here, just don't quote it. It becomes otherwise a JS string instead of a JS object.


Unrelated to the concrete problem, is it absolutely necessary to introduce the extra JSON/jQuery step here? Why don't you just use for example JSTL to let JSP generate the desired HTML in the server side instead of JS/jQuery in the client side?

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555