如何在servlet中读取ajax发送的json [英] How to read json sent by ajax in servlet
本文介绍了如何在servlet中读取ajax发送的json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 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');
}
});
服务端
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
}
}
非常感谢您能提供的任何帮助.
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).
这篇关于如何在servlet中读取ajax发送的json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文