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);
       })}); 
});
4
  • 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 ;) json.org/js.html Commented Aug 30, 2012 at 16:39
  • What does data.length give you? Commented Aug 30, 2012 at 16:41
  • 1
    Did you verify that you are getting valid JSON? jsonlint.com Commented Aug 30, 2012 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. Commented Aug 30, 2012 at 16:52

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.