gpt4 book ai didi

java - 如何在 Servlet 上使用 JSON 将多个参数传递给 Ajax

转载 作者:太空宇宙 更新时间:2023-11-04 06:31:31 24 4
gpt4 key购买 nike

我有 JavaScript 代码,应该从 servlet 获取两个参数:
玩家姓名和玩家类型(人类\计算机)

JavaScript 使用 Ajax 将请求发送到名为:UpdateStatusPaneServlet.java 的 servlet

在我创建的 servlet 上 ArrayList<String> 2 个参数并将其发送到 Ajax。

您可以在图片中看到阵列显示正常。

我不确定如何使用 indexOf() 获取参数功能或者也许我需要使用其他功能。
我也尝试过 get()但没有成功。
另外,对于playerNameAndType[0],它只打印 '['

enter image description here

JavaScript:

function printStatusPane() {

$.ajax({
url: "UpdateStatusPaneServlet",
timeout: 2000,
error: function() {
console.log("Failed to send ajax");
},
success: function(playerNameAndType) {
console.log("GOT ajax: " + playerNameAndType);
$("#currentPlayer").append(playerNameAndType.indexOf(0));
$("#playerType").append(playerNameAndType.indexOf(1));
}
});
}

Servlet(Java):

  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
Gson gson = new Gson();
String currentPlayerNameJSON = "";
String playerTypeJSON = "";
Engine engine = (Engine)getServletContext().getAttribute("engine");
ArrayList<String> JSONRequest = new ArrayList<String>(2);

currentPlayerNameJSON = gson.toJson(engine.GetCurrentPlayer().GetPlayerName());
playerTypeJSON = gson.toJson(engine.GetCurrentPlayer().GetPlayerType().toString());

JSONRequest.add(currentPlayerNameJSON);
JSONRequest.add(playerTypeJSON);
out.print(JSONRequest);

} finally {
out.close();
}
}

最佳答案

根据 D.T. 评论,我修复了它:

  var arrayJson = JSON.parse(playerNameAndType); 
$("#currentPlayer").append(arrayJson[0]);
$("#playerType").append(arrayJson[1]);

并且它打印正确。

关于java - 如何在 Servlet 上使用 JSON 将多个参数传递给 Ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26059060/

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