简体   繁体   中英

How do I use a Java JSONArray with D3 and Dimple, passed using Spring MVC? I'm getting a 404 error

Using Spring MVC, I have a JSONArray in my controller, which I pass to my view using view.addObject like this:

@RequestMapping("/graphWeek")
public ModelAndView getGraphWeek(){
    JSONArray tweetsForWeek = getGraphWeekData();
    ModelAndView mv = new ModelAndView("graphWeek");
    mv.addObject("tweetsForWeek", tweetsForWeek);
    return mv;
}

In my jsp view, I have this:

var svg = dimple.newSvg("#bar", 800, 500);
var src= ${tweetsForWeek};
console.log(src);

d3.json(src, function (error, data) {
  var barChart = new dimple.chart(svg, data);
  barChart.addCategoryAxis("x", ["Day", "Topic"]);
  barChart.addMeasureAxis("y", "Tweets");
  barChart.addSeries("Topic", dimple.plot.bar);
  barChart.addLegend(100, 10, 510, 20, "right");
  barChart.width = 600;
  barChart.height = 400;
  barChart.draw();
});

I added a console.log(src) call to make sure the array was being received by the view and it is. But my graph doesn't display and it gives me an error. This is the result of loading my view, showing the console log and error in firebug:

在此处输入图片说明

So you can see in the console that the array is being received by the view but it is not being handled correctly by d3, does anyone know what could be causing this error? Any help would be greatly appreciated, thanks.

You don't need d3.json here. You have your data already.

var svg = dimple.newSvg("#bar", 800, 500);
var src= ${tweetsForWeek};
console.log(src);

var barChart = new dimple.chart(svg, src); //<-- you have your data already
barChart.addCategoryAxis("x", ["Day", "Topic"]);
barChart.addMeasureAxis("y", "Tweets");
barChart.addSeries("Topic", dimple.plot.bar);
barChart.addLegend(100, 10, 510, 20, "right");
barChart.width = 600;
barChart.height = 400;
barChart.draw();

The alternative here is to, of course, forget using the JSP templating to load your array and do it via JSON:

d3.json("/graphWeek", function (error, data) {
    var svg = dimple.newSvg("#bar", 800, 500);
    var barChart = new dimple.chart(svg, data);
    barChart.addCategoryAxis("x", ["Day", "Topic"]);
    barChart.addMeasureAxis("y", "Tweets");
    barChart.addSeries("Topic", dimple.plot.bar);
    barChart.addLegend(100, 10, 510, 20, "right");
    barChart.width = 600;
    barChart.height = 400;
    barChart.draw();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM