2

On my jsp, this is my code :

 $('.save').on("click",function(){    
    var array = $.map($('table tr'), function (val, i) {
            var obj = {}, inputs = $(val).find('td input:not(:hidden)');
            obj[inputs.filter(':first').val()] = $.map(inputs.not(':first'), function (val, i) {
                return val.value;
            });
            return obj;
        });
        var data = JSON.stringify(array);
        $.post("Controller.html", data, function(response) {
        /// i dont know what to put here,so i think this where i get trouble with
     });
    });

but still data is null when i check on servlet.

this is my servlet :

 protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String data=request.getParameter("data");
        if (data== null) {
            System.out.println("null");
        }
        RequestDispatcher view = request.getRequestDispatcher("/page.jsp");
        view.forward(request, response);
    }

fiddle here

2 Answers 2

3

First you need to send the data, you can use an ajax post method:

$.post("yourservlet", data=JSON.stringify(array), function(response) {
    // handle response from your servlet.
    alert(response)
});

In servlet, you retrieve the data with the command:

String data=request.getParameter("data");

Then you need to parse the json, you can use a library like JSON simple:

Object obj = JSONValue.parse(data);
JSONArray array = (JSONArray) obj;

Or you can manually parse it. Based on your code, your json string will look like this:

data = "[{'orange':['1.00','5']},{'apple':['2.00','5']}]";

You can use split() method or StringTokenizer to separate each object, but you should write your own parser method, for this you can find many tutorials on google.

Sign up to request clarification or add additional context in comments.

10 Comments

can i add this on my jsp file? with no included library? i am new to json and ajax tech
In the server-side, you have a string of data which sent from client. Then you must seperate it to meaning data, it's called parse. And manual parse means you do it yourselft without using any JSON libraries.
thanks, can you give me simple example on how to do it without JSON libraries...please.......
I get the split thing, but why my data is still null? see updated post please.
@Niang is the controller being called? try data:data as the ajax's message
|
0

Javascript is in client-side. And java servlet is for server-side.

You must use ajax to make a call from client-side to your servlet.

1 Comment

I believe that this tutorial is a good start for you: hmkcode.com/java-servlet-send-receive-json-using-jquery-ajax

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.