我有一个奇怪的错误,D3不会接受变量引用的JSON数据,但如果我通过控制台日志将其打印出来并将其复制粘贴到同一个变量中,我会接受它。
所以JSON的这个来源不起作用:
function reformat(data) {
var jsonObject = JSON.parse(data, function(k, v) {
return (typeof v === "object" || isNaN(v)) ? v : parseInt(v, 10);
});
var treeData = (JSON.stringify(makeTree(jsonObject), null, 4));
//etc code for D3
}
但如果我真的通过控制台打印它,并声明它:
treeData = [
{
"id": 1,
"name": "Start",
"children": [
{
"id": 2,
"name": "Decision A",
"children": [
{
"id": 4,
"name": "Possibility A-1",
"children": [
{
"id": 8,
"name": "Consequence A-1"
}
]
},
{
"id": 5,
"name": "Possibility A-2",
"children": [
{
"id": 9,
"name": "Consequence A-2"
}
]
}
]
},
{
"id": 3,
"name": "Decision B",
"children": [
{
"id": 6,
"name": "Possibility B-1",
"children": [
{
"id": 10,
"name": "Consequence B-1"
}
]
},
{
"id": 7,
"name": "Possibility B-2",
"children": [
{
"id": 11,
"name": "Consequence B-2"
}
]
}
]
}
]
}
];
突然工作正常。我无法继续复制和重新声明变量。如果输出相同,为什么不接受呢?
加载网页后,该函数会被调出一次:
function reqListener () {
console.log(this.responseText);
}
var oReq = new XMLHttpRequest();
oReq.onload = function() {
reformat(this.responseText);
};
oReq.open("get", "getData.php", true);
oReq.send();
答案 0 :(得分:3)
为什么要将JSON字符串化并将其传递给treeData?
而不是
var treeData = (JSON.stringify(makeTree(jsonObject), null, 4));
这样做
var treeData = makeTree(jsonObject);
这应该有用。