JSONP breaks in the colon (":")

2

The server sends a JSON, normal. Here is the code:

@GET
@Path("email")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public String getEmail(){
    ViewStatisticsEmail statisticsEmail = new ViewStatisticsEmail();
    statisticsEmail.setDoacoes(1432);
    statisticsEmail.setLidas(5443);
    statisticsEmail.setNaoLidas(4667);
    statisticsEmail.setSent(10000);
    statisticsEmail.setVisualization("Atualizado por ultimo " + Calendar.getInstance().getTime());
    return new Gson().toJson(statisticsEmail);
}

And I'm using ajax to draw a graph with this information. Here is the ajax code:

function chartEmail() {
    var url = 'http://192.168.0.42:8080/Admin/service/email';
    $.ajax({
        type: 'GET',
        url: url,
        dataType: 'jsonp',
        success: function (data) {
            var data = google.visualization.arrayToDataTable([
                ['Task', 'valores'],
                ['Lidas',     data.lidas],
                ['Não lidas',      data.naoLidas],
                ['Doações',  data.doacoes]
            ]);

            var options = {
                title : data.sent,
                legend : "bottom",
                pieHole: 0.4
            };

            var chart = new google.visualization.PieChart(document.getElementById('chart-email'));
            chart.draw(data, options);
        }
    });
  }

It's google charts.

Here comes the following error: Uncaught SyntaxError: Unexpected token :

    
asked by anonymous 12.09.2016 / 15:52

1 answer

1

Since in javascript you expect a JSONP from the server, then the server has to send a JSONP, not a JSON:

@GET
@Path("email")
@Produces("application/javascript")
@Consumes(MediaType.APPLICATION_JSON)
public String getEmail(@QueryParam("callback") String callback) {
    ViewStatisticsEmail statisticsEmail = new ViewStatisticsEmail();
    statisticsEmail.setDoacoes(1432);
    statisticsEmail.setLidas(5443);
    statisticsEmail.setNaoLidas(4667);
    statisticsEmail.setSent(10000);
    statisticsEmail.setVisualization("Atualizado por ultimo " + Calendar.getInstance().getTime());
    String json = new Gson().toJson(statisticsEmail);
    return callback + "(" + json + ")";
}

This code is almost identical to your original code. The differences are:

  • @Produces("application/javascript") - After all, what it produces now is a javascript snippet, not a JSON.

  • @QueryParam("callback") String callback - The callback parameter is essential for JSONP to work.

Relevant source: link

    
12.09.2016 / 17:24