我的项目是用d3.js绘制grahp。我发现了一些PHP代码,这绝对是我想要的。但我正在使用c#和vs.所以我将它转换为asp.net。首先,我想编写一些硬编码数据样本并使用d3.js绘制图像。以及来自该php项目的javascript代码。现在我有一个服务器端webmethod返回json字符串。参数dataSample是Dictionary类型。它看起来像下面,没有任何错误。
返回JsonConvert.SerializeObject(dataSample);
在前端我使用ajax来检索数据。
<script>
$.ajax({
type: 'POST',
url: 'Map.aspx/read_data',
contentType: 'application/json; charset=utf-8',
data: "{ }",
dataType: "json",
success: function(response) {
d3.json("", function (data) {
graph.data = response.d;
drawGraph();
});
},
error: function(error) {
console.log("Wwoops something went wrong !");
}
});
</script>
Ajax调用成功完成,Console日志显示graph.data,响应如下所示
{"DSO":{"name":"DSO","type":"group0","depends":["BPR","Transmission Company","Government"],"dependedOnBy":["TSO","Transmission Company"],"docs":""},"TSO":{"name":"TSO","type":"group1","depends":["BPR","DSO","Producer Secondary Energy","Government"],"dependedOnBy":["Producer Secondary Energy"],"docs":""}}
然后我想循环每个json对象,这样我就可以告诉drawGraph()为每个对象绘制节点,例如:
for (var name in graph.data) {
var obj = graph.data[name];
console.log("name: " + name + "object: " + obj);
我的问题是console.log(&#34;名称:&#34; +名称+&#34;对象:&#34; + obj)未输出Json中的每个对象。它循环每个通信而不是单个对象。
我想输出对象而不是这个。
答案 0 :(得分:1)
You need to parse json to loop it. Do a proper for loop using the parsed variable.
<script>
$.ajax({
type: 'POST',
url: 'Map.aspx/read_data',
contentType: 'application/json; charset=utf-8',
data: "{ }",
// remove this line
//dataType: "json",
success: function(response) {
parsedobj = jQuery.parseJSON(response);
// do your for loop here
},
error: function(error) {
console.log("Wwoops something went wrong !");
}
});
</script>
答案 1 :(得分:0)
正如@shilly所说的那样,你正在循环使用JSON ......
这应该足够了:
var graphDataObject = JSON.parse(graph.data);
for (var name in graphDataObject) {
var obj = graphDataObject[name];
console.log("name: " + name + " object: " + obj);
}
答案 2 :(得分:0)
你必须将JSON.parse字符串作为json,然后循环json对象。
示例:
<script>
var r = JSON.parse('{"DSO":{"name":"DSO","type":"group0","depends":["BPR","Transmission Company","Government"],"dependedOnBy":["TSO","Transmission Company"],"docs":""},"TSO":{"name":"TSO","type":"group1","depends":["BPR","DSO","Producer Secondary Energy","Government"],"dependedOnBy":["Producer Secondary Energy"],"docs":""}}');
for (var g in r) {
for (var c in r[g]) {
console.log(r[g]['name']);
}
}
</script>