gpt4 book ai didi

javascript - 从 Servlet 到 Jquery 的数组的数组

转载 作者:行者123 更新时间:2023-11-28 02:18:24 25 4
gpt4 key购买 nike

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

var derpArray[0] = new array();

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

下面是我的代码:

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

函数加载() {

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

}

最佳答案

编辑在OP添加servlet代码后。

我怀疑你的 servlet 是否能工作。如果是的话,那就是 coincidence 。您可能需要某种 JSON 库来与您的 servlet 一起使用。 json.org/提供了一个简单的 JSON 库,这可能足以满足您的需求。对于更高级的功能,您可以查看类似 Jackson 的库。或JSONSimple .

在前端,您还需要将逻辑作为回调添加到 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"));
});

关于javascript - 从 Servlet 到 Jquery 的数组的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16065553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com