如何读取JSON阿贾克斯在Servlet发送 [英] How to read json sent by ajax in servlet
本文介绍了如何读取JSON阿贾克斯在Servlet发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是新来的Java,我努力奋斗着这个问题了2天,终于决定在这里问。
I'm new to java and I struggling with this problem for 2 days and finally decided to ask here.
我想读的jQuery发送的,所以我可以在我的servlet使用该数据。
I am trying to read data sent by jQuery so i can use it in my servlet
jQuery的
var test = [
{pv: 1000, bv: 2000, mp: 3000, cp: 5000},
{pv: 2500, bv: 3500, mp: 2000, cp: 4444}
];
$.ajax({
type: 'post',
url: 'masterpaket',
dataType: 'JSON',
data: 'loadProds=1&'+test, //NB: request.getParameter("loadProds") only return 1, i need to read value of var test
success: function(data) {
},
error: function(data) {
alert('fail');
}
});
Servlet的
Servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (request.getParameter("loadProds") != null) {
//how do i can get the value of pv, bv, mp ,cp
}
}
我真的AP preciate任何帮助,您可以提供。
I really appreciate any help you can provide.
推荐答案
您将无法解析服务器上,除非你正确地把它:
You won't be able to parse it on the server unless you send it properly:
$.ajax({
type: 'get', // it's easier to read GET request parameters
url: 'masterpaket',
dataType: 'JSON',
data: {
loadProds: 1,
test: JSON.stringify(test) // look here!
},
success: function(data) {
},
error: function(data) {
alert('fail');
}
});
您必须使用 JSON.stringify
来你的JavaScript对象发送的JSON字符串。
You must use JSON.stringify
to send your JavaScript object as JSON string.
然后在服务器上:
String json = request.getParameter("test");
您可以手工解析 JSON
字符串,或使用任何库(我会推荐的 GSON )。
You can parse the json
string by hand, or using any library (I would recommend gson).
这篇关于如何读取JSON阿贾克斯在Servlet发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文