【问题标题】:How to pass multiple parameters with JSON on Servlet to Ajax如何使用 Servlet 上的 JSON 将多个参数传递给 Ajax
【发布时间】:2014-09-26 11:59:59
【问题描述】:

我的 JavaScript 代码应该从 servlet 获取两个参数:
玩家姓名和玩家类型(人\电脑)

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

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

你可以在图片中看到数组看起来没问题。

我不确定如何使用indexOf() 函数获取参数,或者我可能需要使用其他函数。
我也尝试了get(),但没有成功。
同样使用 playerNameAndType[0] 它只打印 '['

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();
        }
    }

【问题讨论】:

  • 您的控制台为 playerNameAndType 打印什么??
  • 您也可以尝试以下方法吗?变种测试 = [];测试 = playerNameAndType;并尝试让 test[0] 打印
  • 尝试使用 JSON.parse(playerNameAndType) 将其转换为 json,然后使用 index.parse 访问它。 var obj = JSON.parse(playerNameAndType); obj[0]
  • @KumarKailash,当我在控制台上输入 playerNameAndType 时:"["Bob", "Human"]"
  • 您说您正在接收 "["Bob", "Human"]" 。只需 $("#currentPlayer").append(playerNameAndType[0]); $("#playerType").append(playerNameAndType[1]);

标签: java javascript jquery ajax servlets


【解决方案1】:

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

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

而且打印正确。

【讨论】:

    【解决方案2】:

    你得到一个对象数组。只需简单地从它的索引中检索对象。

    $("#currentPlayer").append(playerNameAndType[0]);
    $("#playerType").append(playerNameAndType[1]);
    

    【讨论】:

    • 不,正如我在我的问题上写的那样,我试过 playerNameAndType[0] prints '['
    【解决方案3】:

    indexOf返回数组值的位置。使用key index取数组值并追加到id中

    playerNameAndType = ["Bob", "Human"];
    $("#currentPlayer").append(playerNameAndType[0]);
    $("#playerType").append(playerNameAndType[1]);
    

    【讨论】:

      【解决方案4】:

      代替下面的代码

      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);
      

      请尝试

      currentPlayerNameJSON = gson.toJson(engine.GetCurrentPlayer().GetPlayerName());
      playerTypeJSON = gson.toJson(engine.GetCurrentPlayer().GetPlayerType().toString());
      HashMap<String, String> responseMap = new HashMap<String,String>();
      resposeMap.put("name",currentPlayerNameJSON );
      resposeMap.put("type",playerTypeJSON );
      out.print(responseMap.toString());
      

      你可以在javascript中

      function printStatusPane() {
      
          $.ajax({
              url: "UpdateStatusPaneServlet",
              timeout: 2000,
              error: function() {
                  console.log("Failed to send ajax");
              },
              success: function(playerNameAndType) {
                 var json = $.parseJSON(playerNameAndType);    
                  $("#currentPlayer").append(json['name']);
                  $("#playerType").append(json['type']);
              }
          });
      }
      

      【讨论】:

        【解决方案5】:

        您正在返回一个 ArrayList-“JSONRequest”,其中包含来自您的 servlet 的 Json 对象。尝试通过JSON.stringify(JSONRequest) 将您的数组列表转换为 Json。然后您可以在客户端处理此 Json。

        【讨论】:

          【解决方案6】:

          正如你所说,控制台输出是["Bob", "Human"] 你可以通过索引直接访问它:

          $("#currentPlayer").append(playerNameAndType[0]);
          $("#playerType").append(playerNameAndType[1]);
          

          indexof() 返回的是你传入参数的元素的索引。

          playerNameAndType.indexOf("Bob")
          

          会给你0,“Bob”的索引。

          例子:

          var person = ["Bob", "Human"];
          document.write("Hey, " + person[0] + "!! You are first in array.");

          【讨论】:

          • 不,正如我在我的问题上写的那样,我试过 playerNameAndType[0] prints '['
          • 但我没有收到 "var person = ["Bob", "John"];"我从 servlet 收到一些 ArrayList 对象,其中包含两个对象和 playerNameAndType[0] 打印 '['
          • 在评论问题时你说控制台输出是["Bob", "Human"]。不幸的是,SO 代码运行器不支持 java 代码! :( 我不能在这里提供可运行的 java 代码......!!所以我使用一个变量来存储你的控制台输出的确切内容。
          猜你喜欢
          • 1970-01-01
          • 2010-09-19
          • 2013-06-01
          • 2013-09-27
          • 1970-01-01
          • 2010-12-27
          • 2013-01-06
          • 1970-01-01
          • 2023-03-17
          相关资源
          最近更新 更多