1

我目前正在尝试让一个 servlet 向我的 javascript jquery 代码返回一个数组数组。我遇到的问题是,如果我想在 jQuery 中有一个数组数组,我不得不说

var derpArray[0] = new array();

这带来了一个问题,因为我可能不知道我将从服务器返回多少行。目前我正试图让我的 servlet 返回一个数组数组,分配给一个 javascript 变量,然后根据这些值创建一个表。任何提示将不胜感激。

下面是我的代码:

Java 小服务程序:

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 = 加载;

函数加载(){

$.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";

}

4

1 回答 1

1

OP 添加 servlet 代码后编辑。

我怀疑你的 servlet 会起作用。如果是这样,那将是巧合。您可能需要某种 JSON 库来与您的 servlet 一起使用。json.org/提供了一个简单的 JSON 库,它可能足以满足您的需求。对于更高级的功能,您可以查看JacksonJSONSimple等库。

在前端,您还需要将逻辑作为回调添加到get()函数中,因为它是异步的(使用getJSON可能会更好,因为您计划发回 JSON)。您需要增加内部循环中“sourceFileData”的索引,而不是将其硬编码为 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"));
});
于 2013-04-17T16:42:33.517 回答