1

我想对服务器进行 ajax 调用。直到现在我一直使用:

$.get("/FruitResults?fruit="+fruitname+"&color="+colorname,function(data){addToTables(data);},"text");

用于发送参数水果,颜色。现在如果我有很多水果,它们的颜色,价格..

{apple:{color:red,price:30},orange:{color:orange,price:10}}

和这么大的水果列表,我应该如何使用 Ajax 调用将其发送到 servlet。,以什么格式?在 servlet 方面,我应该如何从请求对象中检索请求参数?

4

1 回答 1

3

Httpget方法不适合发送复杂数据。因此,您必须使用post方法将复杂数据从客户端发送到服务器。您可以使用 JSON 格式对这些数据进行编码。示例代码如下:

var fruits = {apple:{color:red,price:30},orange:{color:orange,price:10}};
$.post("/FruitResults", JSON.stringify(fruits), function(response) {
    // handle response from your servlet.
});

请注意,由于您使用了该post方法,因此您必须在 servlet 的方法中处理此请求,doPost而不是doGet. 要检索发布的数据,您必须读取 servlet 请求的输入流,如下所示:

public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

  String jsonString = new String(); // this is your data sent from client
  try {
    String line = "";
    BufferedReader reader = request.getReader();
    while ((line = reader.readLine()) != null)
      jsonString += line;
  } catch (Exception e) { 
    e.printStackTrace();
  }

  // you can handle jsonString by parsing it to a Java object. 
  // For this purpose, you can use one of the Json-Java parsers like gson**.
}

** gson链接:http ://code.google.com/p/google-gson/

于 2013-10-17T12:46:43.313 回答