我想对服务器进行ajax get调用。现在我总是使用:
$.get("/FruitResults?fruit="+fruitname+"&color="+colorname,function(data){addToTables(data);},"text");
发送参数水果,颜色。如果我有很多水果,他们的颜色,价格..
{apple:{color:red,price:30},orange:{color:orange,price:10}}
以及如此大的水果列表,我是如何使用Ajax调用将其发送到servlet的,以什么格式? 而在servlet方面,我该如何从请求对象中检索请求参数?
Http get
方法不适合发送复杂数据。 因此,必须使用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/
以上就是jQuery教程分享将数据从Javascript发送到Servlet相关内容,想了解更多jQuery开发(异常处理)及jQuery教程关注计算机技术网(www.ctvol.com)!)。
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/jquerytutorial/558038.html