0

I have this method in controller

@RequestMapping(value = "/updateWithParams", method = RequestMethod.GET)
    @ResponseBody
    public List<ResolutionDto> updateWithParams() {
        List<ResolutionDto> list = new ArrayList<>();
        List<Resolution> resolutions = resolutionService.findAll();
        for (Resolution resolution : resolutions) {
            list.add(new ResolutionDto(resolution.getId(), resolution.getName(), resolution.getStatus(), resolution.getDateCreated(), resolution.getUserName()));
        }
        return list;
    }

It is ResolutionDto

@Data
@AllArgsConstructor
public class ResolutionDto {
    public Long id;
    private String name;
    private Integer status;
    private Date dateCreated;
    private String userName;
}

And on Client side I want get this array like JSON array and fill jQuery DataTable.

function loadTable() {
        $.ajax({
            type: 'GET',
            dataType: "json",
            url: '/updateWithParams',
            success: function (data) {
                var jsdata = JSON.parse(data);
                var datatable = $('#example').dataTable().api();
                datatable.fnAddData(jsdata);
            },
            error: function (xhr, str) {
                alert("error");
            }
        });
    }

But it not work. I thik problem in this line var jsdata = JSON.parse(data);

but I do not understand how fix it

user5620472
  • 2,722
  • 8
  • 44
  • 97
  • If you could add in the DataTable initialization javascript that might be helpful as well. Just in case the issue is in the DataTable options. – Adrian Nov 21 '16 at 10:42

2 Answers2

0

Let's forget about the Ajax stuff for a moment as yours looks fine.

There's nothing wrong with the JSON.parse(data), its just redundant as dataType: "json" indicates that the type of data that you're expecting back from the server is JSON.

Now put this in your controller method (just before the iteration part):

if (resolutions .isEmpty()) {
System.out.print("The resolutions list is empty!");
}

If so, that's the problem, the DTO's properties are not being assigned with any values, therefore the list is literally empty. If that is the case then there's nothing people can do as you didn't include your service, so nobody can't afford to see how the data initialized or constructed on which parts of your codes.

Fevly Pallar
  • 3,059
  • 2
  • 15
  • 19
0

JSON.parse() is not needed anymore, because it was automatically parsed. Try this:

$.ajax({
url: "url",
type: "get|post",
contentType: "application/json",
success: function(data) {
// try printing, to test
data.foreach(function(obj, index)) {
console.log(obj.name);
}
}
    });
Haze
  • 195
  • 7