27

我是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');
    }
});

小服务程序

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
   }
}

我非常感谢您能提供的任何帮助。

4

3 回答 3

29

除非您正确发送,否则您将无法在服务器上解析它:

$.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 字符串发送。

然后在服务器上:

String json = request.getParameter("test");

您可以手动解析json字符串,也可以使用任何库(我推荐gson)。

于 2013-10-24T14:23:20.470 回答
5

您必须使用 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
}

您将需要一个 json 库(例如 Jackson)来解析 json

于 2013-10-24T14:02:36.433 回答
0

使用 import org.json.JSONObject 而不是 import org.json.simple.JSONObject 对我有用。

请参阅如何从包含 Java 中的 ':' 、'[' 和 ']' 等字符的字符串创建 Json 对象

于 2014-10-13T20:43:17.160 回答