Vernah
Vernah

Reputation: 81

Array of Array from Servlet to Jquery

I'm currently trying to have a servlet return an array of arrays to my javascript jquery code. The issue I'm having is that if I want to have an array of arrays in jQuery, I have to say

var derpArray[0] = new array();

This poses a problem since I may not know how many rows I'll be returning from a server. At the moment I'm attempting to have my servlet return an array of array, assign to a javascript variable, then create a table out of the values. Any hints would be appreciated.

Here is my code below:

Java Servlet:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String[][] sourceFiles = null;
    System.out.println("PING");

    try{
        sourceFiles = WebAppDB2Connector.getTopRows(5);
    }
    catch (Exception e)
    {
        SimpleLogger.logInfo("Error retrieving data..." + e.getMessage());
    }

    Gson gson = new Gson();
    String json = gson.toJson(sourceFiles);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);

    System.out.println("end");


}

JavaScript:

window.onload = load;

function load() {

$.getJSON("http://localhost:9194/MyWebApplication/SourceFile", function(sourceFileData) {

var table = $("<table></table>");
for (var i = 0; i < sourceFileData.length; i++) 
{
    var line = $("<tr></tr>");
    for (var j = 0; j < sourceFileData[i].length; j++)
    {
        line.append( $(cell).html('<td>' + sourceFileData[i][j] + '</td>'));
    }
    table.append(line);
}

table.appendTo( $("#sourceFileTable"));

});

document.getElementById("test").innerHTML = "LOL";

}

Upvotes: 1

Views: 938

Answers (1)

colestrode
colestrode

Reputation: 10658

EDIT after OP added servlet code.

I doubt that your servlet would work. If it did, it would be coincidence. You will probably need some sort of JSON library to use with your servlet. json.org/ provides a simple JSON library, which is probably good enough for your needs. For more advanced features you can look at libraries like Jackson or JSONSimple.

On the front end, You'll also want to add your logic as a callback to the get()function since it is asynchronous (it's probably better to use the getJSON instead, since you are planning on sending back JSON). And you'll need to increment the index of 'sourceFileData' in the innerloop, instead of hard coding it to 0:

 $.getJSON("http://localhost:13839/MyWebApplication/SourceFile", function(sourceFileData) {

    var table = $("<table></table>");
    for (var i = 0; i < sourceFileData.length; i++) 
    {
        var line = $("<tr></tr>");
        for (var j = 0; j < sourceFileData[i].length; j++)
        {
            line.append( $(cell).html('<td> + sourceFileData[i][j] + '</td>'));
        }
        table.append(line);
    }

    table.appendTo( $("#sourceFileTable"));
});

Upvotes: 1

Related Questions