我在d3.json函数中使用URL,数据显示未定义。
My code here
==============
var jsonURL = "http://192.168.7.102:8080/restful/traffic/json/get";
d3.json(jsonURL, function(error, data){
alert(data);
});
执行时数据显示未定义。我创建了restful web服务应用程序以使用上面的URL获取数据,它返回JSONArray。
@GET
@Path("/json/get")
@Produces(MediaType.APPLICATION_JSON)
public JSONArray startReading() throws JSONException {
String json = null;
String newJson = null;
try {
URL url = new URL("http://192.168.7.102:3000/data/traffic");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
while ((json = br.readLine()) != null) {
newJson = json;
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
JSONArray array = new JSONArray(newJson);
return array;
}
当我访问浏览器中的URL时,显示数据。但是在d3.json函数中它显示的是undefined而不是data。因此,我无法在浏览器中显示图表。请指导我在哪里做错了。
答案 0 :(得分:0)
var data;
d3.json("http://192.168.7.102:8080/restful/traffic/json/get", function(error, json) {
if (error) return console.warn(error);
data = json;
visualizeit();
});