简体   繁体   English

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

[英]How to pass multiple parameters with JSON on Servlet to Ajax

I have JavaScript code that should get two parameters from servlet: 我有应该从servlet获取两个参数的JavaScript代码:
player name and player type (Human \\ Computer) 播放器名称和播放器类型(人类\\计算机)

The JavaScript use Ajax to send the request to the servlet named: UpdateStatusPaneServlet.java JavaScript使用Ajax将请求发送到名为UpdateStatusPaneServlet.java的servlet。

On the servlet I created ArrayList<String> of 2 parameters and sent it to the Ajax. 在Servlet上,我创建了2个参数的ArrayList<String>并将其发送到Ajax。

You can see in the picture that the array appears ok. 您可以在图片中看到该阵列显示正常。

I am not sure how to get the parameters using the indexOf() function or maybe I need to use other function. 我不确定如何使用indexOf()函数获取参数,或者可能需要使用其他函数。
I also tried with get() but it didn't work. 我也尝试了get()但是没有用。
Also with playerNameAndType[0] it just print '[' 同样使用playerNameAndType [0]它只打印'['

在此处输入图片说明

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

Following DT comment I fixed it: 在DT评论之后,我对其进行了修复:

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

And it prints it correctly. 并正确打印。

indexOf returns the position of the array value.Use key index to take the array value and append in to the id indexOf返回数组值的位置,使用键索引获取数组值并附加到id中

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

As you said, console output is ["Bob", "Human"] You can access that directly by index : 如您所说,控制台输出为["Bob", "Human"]您可以直接通过index进行访问:

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

What indexof() return is index of element you passed in argument. indexof()返回的是您在参数中传递的元素的索引。

playerNameAndType.indexOf("Bob")

will give you 0 , the index of "Bob". 将为您提供0 ,即“鲍勃”的索引。

Example : 范例:

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

you are getting an array of objects . 您将得到一系列对象。 Just simply retrieve the object from it's index . 只需从其index检索对象即可。

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

Instead of the below code 代替下面的代码

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

Please try 请试试

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

and in the javaScript you can 在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']);
        }
    });
}

You are returning an ArrayList-"JSONRequest" having Json objects from your servlet. 您正在从Servlet返回具有Json对象的ArrayList-“ JSONRequest”。 Try converting your arraylist to Json by JSON.stringify(JSONRequest) . 尝试通过JSON.stringify(JSONRequest)转换为Json。 You can then handle this Json in client side. 然后,您可以在客户端处理此Json。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM