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/