Search code examples
javahtmlajaxjspdwr

Use an Ajax response in JSP


I have a JSP page which has nothing but a normal HTML table with five rows and five columns.

Now I am making an Ajax call and get a response back. Now once I have the response back, I need the data to be filled in appropriate cells of the table.

So my question is;

  1. Should I use JSON for building the response?
  2. How do I handle the data back at the JSP level. That is, once I have the response from the server?

Just as additional information, I am using DWR which is nothing but calling a Java method (which builds the response) from inside JavaScript code.


Solution

  • Let's consider this Java class.

        class Employee
        {
            int id;
            String eName;
            // Setters and getters
        }
    

    In JavaScript, the JSON object:

     var employee = {
         id   : null,
         name : null
     };
    

    This is the call to a Java method from a JavaScript function:

       EmployeeUtil.getRow(employee,dwrData);
    

    In getRow() of the EmployeeUtil class, the return type of method will be Employee:

       Employee getRow();
    

    So using the setters of Employee set the data. dwrData is the callback function.

    function dwrData(data) {
        employee=data;
    }
    

    The data returned, which is an Employee bean, will be in the callback function.

    Just initialize this in the JavaScript JSON object.

    Use a JSON object accordingly to populate the table.

    EDIT :

    You can use List getRow() instead of Employee getRow(), returning a list of rows as a List instead of a Bean.

    Now the response contains list as data.

    Refer to Populate rows using DWR.

    Check these examples to populate data in table:

    Should I use JSON for building the response?

    • No need to pass JSON in response. Instead return a Bean of a class as mentioned above.

    • A list can be passed as a response, also as mentioned above.

    How do I handle the data back at the JSP level. That is, once I have the response from the server.

    Check the explanation above and the examples of the given links to handle the response in JSP and display the response data in a table.