gpt4 book ai didi

javascript - Ajax检索Json字符串但无法将成功数据作为对象循环

转载 作者:行者123 更新时间:2023-12-03 08:06:35 25 4
gpt4 key购买 nike

我的项目是用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 调用成功完成,控制台日志显示 graph.data,即 response.d,如下所示

{"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("name: "+ name + "object: "+ obj) 没有输出 Json 中的每个对象。它循环每个字母而不是单个对象。

不正确的console.log输出是 enter image description here

我想输出对象而不是这个。

最佳答案

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>

关于javascript - Ajax检索Json字符串但无法将成功数据作为对象循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34356398/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com