Yos*_*yan 26 java ajax jquery json servlets
我是java的新手,我在这个问题上苦苦挣扎了2天,最后决定在这里问一下.
我试图读取jQuery发送的数据,所以我可以在我的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');
}
});
Run Code Online (Sandbox Code Playgroud)
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
}
}
Run Code Online (Sandbox Code Playgroud)
我非常感谢您提供的任何帮助.
sil*_*edh 28
除非您正确发送,否则您将无法在服务器上解析它:
$.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');
}
});
Run Code Online (Sandbox Code Playgroud)
您必须使用JSON.stringify将JavaScript对象作为JSON字符串发送.
然后在服务器上:
String json = request.getParameter("test");
Run Code Online (Sandbox Code Playgroud)
您可以json手动解析字符串,也可以使用任何库(我建议使用gson).
您必须使用JSON解析器将数据解析为Servlet
import org.json.simple.JSONObject;
// this parses the json
JSONObject jObj = new JSONObject(request.getParameter("loadProds"));
Iterator it = jObj.keys(); //gets all the keys
while(it.hasNext())
{
String key = it.next(); // get key
Object o = jObj.get(key); // get value
System.out.println(key + " : " + o); // print the key and value
}
Run Code Online (Sandbox Code Playgroud)
你需要一个json库(例如Jackson)来解析json