Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

java - How to read json sent by ajax in servlet

I'm new to java and I struggling with this problem for 2 days and finally decided to ask here.

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

You must use JSON.stringify to send your JavaScript object as JSON string.

And then on the server:

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

You can parse the json string by hand, or using any library (I would recommend gson).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...