未捕获SyntaxError:JSON输入意外结束 [英] Uncaught SyntaxError: Unexpected end of JSON input
问题描述
我想根据输入获得d3设计
MySQL表
value id name parent
A 1 A 0
A 2 A1 1
A 3 A2 1
B 4 B 0
B 5 B1 4
php代码将mysql数据转换为j3格式以在d3中使用
UPDATED PHP和JSON结果基于@ Z-BONE答案
index.php
<?php
if(isset($ _ GET ['input']))
{
$ con = mysqli_connect(localhost,root,admin321,php);
if(mysqli_connect_errno())
{
echo无法连接到MySQL:。 mysqli_connect_error();
}
$ name = $ _ GET ['input'];
$ sql =SELECT * FROM tab where value LIKE'%。$ name。%';
$ r = mysqli_query($ con,$ sql);
$ data = array();
while($ row = mysqli_fetch_assoc($ r)){
$ data [] = $ row;
}
function buildtree($ src_arr,$ parent_id = 0,$ tree = array())
{
foreach($ src_arr as $ idx => $ row)
{
if($ row ['parent'] == $ parent_id)
{
foreach($ row as $ k => $ v)
$ tree [$ row ['id']] [$ k] = $ v;
unset($ src_arr [$ idx]);
$ tree [$ row ['id']] ['children'] = buildtree($ src_arr,$ row ['id']);
}
}
ksort($ tree);
return $ tree;
}
function insertIntoNestedArray(& $ array,$ searchItem){
if($ searchItem ['parent'] == 0){
array_push($ array,$ searchItem);
return;
}
if(empty($ array)){return; }
array_walk($ array,function(& $ item,$ key,$ searchItem){
if($ item ['id'] == $ searchItem ['parent']){
array_push($ item ['children'],$ searchItem);
return;
}
insertIntoNestedArray ,$ searchItem);
}
$ nestedArray = array();
foreach($ data as $ itemData){
$ nestedArrayItem ['id'] = $ itemData ['id'];
$ nestedArrayItem ['name'] = $ itemData ['name'];
$ nestedArrayItem ['parent'] = $ itemData ['parent'];
$ nestedArrayItem ['children'] = array();
insertIntoNestedArray($ nestedArray,$ nestedArrayItem);
}
header('Content-Type:application / json');
$ json = json_encode($ nestedArray);
echo $ json;
}
?>
PHP的json结果低于我的输入(B)
[
{
id:4,
name:B,
parent:0,
children:[
{
id:5,
name:B1,
parent:4,
children:[
]
}
]
}
]
更新前的PHP和JSON结果如下 - http://pastebin.com/409DfSuQ
我使用
echo $ json = substr($ json,1,-1);
在这里,删除第一个和最后一个括号,给出无法读取foreach的属性错误。
draw.html
< html>
< head>
< meta http-equiv =Content-Typecontent =text / html; charset = utf-8>
< title>绘制< / title>
< / head>
< body>
< form name =vinformmethod =get>
< input type =textname =input>
< input type =submitvalue =Showid =display>
< / form>
< div id =content>
< / div>
< / body>
< / html>
如果我使用
运行此代码 < form name =vinformmethod =getaction =index.php>
输出是一个有效的json ..我也试过将这个json复制到一个单独的文件,并使用在d3 ...工作正常...
但问题是当我使用draw.html文件与
< form name =vinformmethod =getaction =index.html>
它会显示 this
,此错误带我到index.html中的这一行
d3.json(index.php,function(error,flare){
if(error)throw error; //显示json输入意外结束
我的index.html是
<!DOCTYPE html>
< html>
< head>
< title> Radial Cluster Demo< / title>
< script src =// d3js.org/d3.v3.min.js\"> ;</script>
< style>
.node {
cursor:pointer;
}
.overlay {
background-color:white;
}
.node circle {
fill:#fff;
stroke:steelblue;
stroke-width:1.5px;
}
.node text {
font:sans-serif;
font-size:80%;
text-align : 中央;
}
.link {
fill:none;
}
.parent {
fill:red;
}
div#tooltip {
position:absolute;
font:15px sans-serif;
background:orange;
border-radius:8px;
padding-left:5px;
padding-right:5px;
pointer-events:none;
}
< / style>
< / head>
< body>
< div id =tooltipstyle =display:none>< / div>
< div id =tree-containerclass =full>< / div>
< script type =text / javascript>
var selectedNode = null;
var draggingNode = null;
var panSpeed = 200;
var panBoundary = 0;
var i = 0;
var duration = 750;
var root;
var width = 5000;
var height = 5000;
var diameter = 750;
var tree = d3.layout.tree()。size([360,diameter / 2 - 120])
.separation(function(a,b){
return(a.parent == b.parent?1:5)/ a.depth;
});
var diagonal = d3.svg.diagonal.radial()
.projection(function(d){
return [dy,dx / 180 * Math.PI];
});
d3.select(self.frameElement).style(height,width);
function sortTree(){
tree.sort(function(a,b){
return b.name.toLowerCase a.name.toLowerCase()?1:-1;
});
}
sortTree();
var baseSvg = d3.select(#tree-container)。append(svg)
.attr(width,width)
.attr(height )
.attr(class,overlay)
.attr(transform,translate(+ 1000 +,+ 1000 +));
函数expand(d){
if(d._children){
d.children = d._children;
d.children.forEach(expand);
d._children = null;
}
}
d3.json(index.php,function(error,flare){
if(error)throw error;
root = flare;
root.x0 = height / 2;
root.y0 = 0;
函数collapse(d){
if(d.children){
d._children = d.children;
d._children.forEach(collapse);
d.children = null;
}
update(d);
}
flare.children.forEach(collapse);
update(root);
function toggleChildren(d){
if(d.children){
d._children = d.children;
d.children = null;
} else if(d._children){
d.children = d._children;
d._children = null;
}
return d;
}
function click(d){
if(!d.children)
root.children.forEach(collapse);
// d。 children = d._children;
// d._children = null;
if(d3.event.defaultPrevented)return;
d = toggleChildren(d);
update(d);
}
函数更新(源){
var levelWidth = [1];
var childCount = function(level,n){
if(n.children& n.children.length> 0){
if(levelWidth.length& + 1)levelWidth.push(0);
levelWidth [level + 1] + = n.children.length;
n.children.forEach(function(d){
childCount(level + 1,d);
});
}
};
childCount(0,root);
var nodes = tree.nodes(root);
links = tree.links(nodes);
node = svgGroup.selectAll(g.node)
.data(nodes,function(d){
return d.id ||(d.id = ++ i)
});
var nodeEnter = node.enter()。append(g)
.attr(class,node)
.on('click',click);
nodeEnter.append(circle)
.attr(class,smallcircle)
.style(stroke,function(d){return d。颜色;});
nodeEnter.append(text)
.text(function(d){return d.name;})
// .style ,12px serif)
.style(opacity,1)
.style(fill-opacity,0)
.on {
var r = d3.select(this).node()。getBoundingClientRect();
d3.select(div#tooltip)
.style(display,inline
.style(top,(r.top-25)+px)
.style(top,10 +px)
.style left,(d3.event.pageX)+px)
.style(top,(d3.event.pageY - 40)+px)
.style ,r.left + 40+px)
.style(left,+px)
.style(position,absolute)
.text );
})
.on(mouseout,function(){
d3.select(div#tooltip)。style(display,none)
});
node.select(circle.nodeCircle)
.attr(r,4.5)
.style(fill,function {return d._children?red:#fff;});
//});
var nodeUpdate = node.transition()
.duration(duration)
.attr(transform,function(d){return
rotate(+(dx- 90)+)translate
(+ dy +)rotate(+(-dx + 90)+);});
nodeUpdate.select(circle)。attr(r,4.5)
.style(fill,function(d){return d._children?
lightsteelblue:#fff;});
nodeUpdate.select(text)
.style(fill-opacity,4)
.attr(fill,function(d){return .children?red:black);})
.attr(stroke-width,function(d)
{return(d.children?4:1) ;})
.attr(stroke-width,function(d)
{return(d.children?4 px:1 px);})
.attr(dy,.35em)
.attr(text-anchor,function(d){
return dx< 180?start:end
})
.attr(transform,function(d){
return dx< 180? 360)translate(-8);
});
var nodeExit = node.exit()。transition()
.duration(duration)
.attr(transform,function(d){
return translate(+ source.x +,+ source.y +);})
.remove();
nodeExit.select(circle)
.attr(r,0);
nodeExit.select(text)
.style(fill-opacity,0);
var link = svgGroup.selectAll(path.link)
.data(links,function(d){
return d.target.id;
})
link.style(stroke,function(d){
return d.color;
})
link.enter ).insert(path,g)
.attr(class,link)
link.style(stroke,function(d){
return d .target.color;
})
.attr(d,function(d){
var o = {
x:source.x0,
y:source .y0
};
return diagonal({
source:o,
target:o
});
});
link.transition()
.duration(duration)
.attr(d,diagonal)
link.exit()。transition()
.duration(duration)
.attr(d,function(d){
var o = {
x:source.x,
y:source.y
};
返回对角线({
source:o,
target:o
});
})
.remove();
nodes.forEach(function(d){
d.x0 = d.x;
d.y0 = d.y;
});
}
});
var svgGroup = baseSvg.append(g)
.attr(transform,translate(+ 550 +,+ 300 +));
d3.selectAll(text)。style(fill,function(d)
{return d3.select(this).classed(d.cond, true);});
< / script>
< / body>
< / html>关于这个问题的任何想法???h2_lin>解决方案在您的PHP文件中:
- 您正在使用HTML覆盖内容类型json删除此行
header('Content-Type:text / html; charset = utf-8');
>
- 此外,为什么要用这行删除根括号:
echo $ json = substr($ json,1,-1);
?它会使json无效..只是回传JSON编码的数组,因为..
I am trying to get d3 design based on input
MySQL table
value id name parent A 1 A 0 A 2 A1 1 A 3 A2 1 B 4 B 0 B 5 B1 4
php code to get mysql data into json format to use in d3
UPDATED PHP AND JSON RESULT BASED ON @Z-BONE ANSWER
index.php
<?php if(isset($_GET['input'])) { $con=mysqli_connect("localhost","root","admin321","php"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $name=$_GET['input']; $sql="SELECT * FROM tab where value LIKE '%".$name."%'"; $r = mysqli_query($con,$sql); $data = array(); while($row = mysqli_fetch_assoc($r)) { $data[] = $row; } function buildtree($src_arr, $parent_id = 0, $tree = array()) { foreach($src_arr as $idx => $row) { if($row['parent'] == $parent_id) { foreach($row as $k => $v) $tree[$row['id']][$k] = $v; unset($src_arr[$idx]); $tree[$row['id']]['children'] = buildtree($src_arr, $row['id']); } } ksort($tree); return $tree; } function insertIntoNestedArray(&$array, $searchItem){ if($searchItem['parent'] == 0){ array_push($array, $searchItem); return; } if(empty($array)){ return; } array_walk($array, function(&$item, $key, $searchItem){ if($item['id'] == $searchItem['parent']){ array_push($item['children'], $searchItem); return; } insertIntoNestedArray($item['children'], $searchItem); }, $searchItem); } $nestedArray = array(); foreach($data as $itemData){ $nestedArrayItem['id'] = $itemData['id']; $nestedArrayItem['name'] = $itemData['name']; $nestedArrayItem['parent'] = $itemData['parent']; $nestedArrayItem['children'] = array(); insertIntoNestedArray($nestedArray, $nestedArrayItem); } header('Content-Type: application/json'); $json= json_encode($nestedArray); echo $json ; } ?>
json result from PHP is below based on my input (B)
[ { "id":"4", "name":"B", "parent":"0", "children":[ { "id":"5", "name":"B1", "parent":"4", "children":[ ] } ] } ]
BEFORE UPDATE PHP AND JSON RESULT IS as here - http://pastebin.com/409DfSuQ
I used
echo $json = substr($json, 1, -1);
here ,to remove the first and last brackets which give "cannot read property of foreach"error in D3.
draw.html
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title> draw</title> </head> <body> <form name="vinform"method="get"> <input type="text" name="input"> <input type="submit" value="Show" id="display"> </form> <div id="content"> </div> </body> </html>
if I run this code with
<form name="vinform"method="get"action="index.php">
the output is A valid json..and i also tried copying this json into a separate file and used in d3...that works fine... but the problem is when i used the draw.html file with
<form name="vinform"method="get"action="index.html">
it shows this and this error take me to this line in index.html
d3.json("index.php", function(error,flare) { if (error) throw error; //shows Unexpected end of json input
my index.html is
<!DOCTYPE html> <html> <head> <title>Radial Cluster Demo</title> <script src="//d3js.org/d3.v3.min.js"></script> <style> .node { cursor: pointer; } .overlay { background-color:white; } .node circle { fill: #fff; stroke: steelblue; stroke-width: 1.5px; } .node text { font: sans-serif; font-size: 80%; text-align: center; } .link { fill: none; } .parent{ fill :red; } div#tooltip { position: absolute; font: 15px sans-serif; background: orange; border-radius: 8px; padding-left: 5px; padding-right: 5px; pointer-events: none; } </style> </head> <body> <div id="tooltip" style="display:none"></div> <div id="tree-container"class="full"></div> <script type="text/javascript"> var selectedNode = null; var draggingNode = null; var panSpeed = 200; var panBoundary = 0; var i = 0; var duration = 750; var root; var width = 5000; var height = 5000; var diameter = 750; var tree = d3.layout.tree().size([360, diameter / 2 - 120]) .separation(function (a, b) { return (a.parent == b.parent ? 1 : 5) / a.depth; }); var diagonal = d3.svg.diagonal.radial() .projection(function (d) { return [d.y, d.x / 180 * Math.PI]; }); d3.select(self.frameElement).style("height", width); function sortTree() { tree.sort(function (a, b) { return b.name.toLowerCase() < a.name.toLowerCase() ? 1 : -1; }); } sortTree(); var baseSvg = d3.select("#tree-container").append("svg") .attr("width", width) .attr("height", height) .attr("class", "overlay") .attr("transform", "translate(" + 1000 + "," + 1000 + ")"); function expand(d) { if (d._children) { d.children = d._children; d.children.forEach(expand); d._children = null; } } d3.json("index.php", function(error,flare) { if (error) throw error; root = flare; root.x0 = height / 2; root.y0 = 0; function collapse(d) { if (d.children) { d._children = d.children; d._children.forEach(collapse); d.children = null; } update(d); } flare.children.forEach(collapse); update(root); function toggleChildren(d) { if (d.children) { d._children = d.children; d.children = null; } else if (d._children) { d.children = d._children; d._children = null; } return d; } function click(d) { if (!d.children) root.children.forEach(collapse); //d.children = d._children; // d._children = null; if (d3.event.defaultPrevented) return; d = toggleChildren(d); update(d); } function update(source) { var levelWidth = [1]; var childCount = function (level, n) { if (n.children && n.children.length > 0) { if (levelWidth.length <= level + 1) levelWidth.push(0); levelWidth[level + 1] += n.children.length; n.children.forEach(function (d) { childCount(level + 1, d); }); } }; childCount(0, root); var nodes = tree.nodes(root); links = tree.links(nodes); node = svgGroup.selectAll("g.node") .data(nodes, function (d) { return d.id || (d.id = ++i); }); var nodeEnter = node.enter().append("g") .attr("class", "node") .on('click', click); nodeEnter.append("circle") .attr("class", "smallcircle") .style("stroke", function(d) { return d.color;}); nodeEnter.append("text") .text(function (d) { return d.name; }) // .style("font", "12px serif") .style("opacity", 1) .style("fill-opacity", 0) .on("mouseover", function (d) { var r = d3.select(this).node().getBoundingClientRect(); d3.select("div#tooltip") .style("display", "inline") .style("top", (r.top-25) + "px") .style("top", 10 + "px") .style("left", (d3.event.pageX) + "px") .style("top", (d3.event.pageY - 40) + "px") .style("left", r.left + 40+"px") .style("left", + "px") .style("position", "absolute") .text(d.t); }) .on("mouseout", function(){ d3.select("div#tooltip").style("display", "none") }); node.select("circle.nodeCircle") .attr("r", 4.5) .style("fill", function (d) { return d._children ? "red" : "#fff"; }); // }); var nodeUpdate = node.transition() .duration(duration) .attr("transform", function (d) { return "rotate(" + (d.x - 90) + ")translate (" + d.y + ")rotate(" + (-d.x + 90) + ")"; }); nodeUpdate.select("circle").attr("r", 4.5) .style("fill", function (d) {return d._children ? "lightsteelblue" : "#fff";}); nodeUpdate.select("text") .style("fill-opacity", 4) .attr("fill",function(d){return (d.children?"red":"black");}) .attr("stroke-width",function(d) {return (d.children?"4":"1");}) .attr("stroke-width",function(d) {return (d.children?"4 px":"1 px");}) .attr("dy", ".35em") .attr("text-anchor", function (d) { return d.x < 180 ? "start" : "end"; }) .attr("transform", function (d) { return d.x < 180 ? "translate(8)" : "rotate(360)translate(-8)"; }); var nodeExit = node.exit().transition() .duration(duration) .attr("transform", function (d) { return "translate(" + source.x + "," + source.y + ")"; }) .remove(); nodeExit.select("circle") .attr("r", 0); nodeExit.select("text") .style("fill-opacity", 0); var link = svgGroup.selectAll("path.link") .data(links, function (d) { return d.target.id; }) link.style("stroke", function(d) { return d.color; }) link.enter().insert("path", "g") .attr("class", "link") link.style("stroke", function(d) { return d.target.color; }) .attr("d", function (d) { var o = { x: source.x0, y: source.y0 }; return diagonal({ source: o, target: o }); }); link.transition() .duration(duration) .attr("d", diagonal); link.exit().transition() .duration(duration) .attr("d", function (d) { var o = { x: source.x, y: source.y }; return diagonal({ source: o, target: o }); }) .remove(); nodes.forEach(function (d) { d.x0 = d.x; d.y0 = d.y; }); } }); var svgGroup = baseSvg.append("g") .attr("transform", "translate(" + 550 + "," + 300 + ")"); d3.selectAll("text").style("fill", function (d) { return d3.select(this).classed(d.cond, true); }); </script> </body> </html>
Any idea about this problem???
解决方案In your PHP file:
- You are overriding content type json with HTML... Remove this line
header('Content-Type: text/html; charset=utf-8');
and leave the line before it which declares json...- Also why are you removing the root brackets with this line:
echo $json = substr($json, 1, -1);
? It will make json invalid.. Just echo the JSON encoded array as is..
这篇关于未捕获SyntaxError:JSON输入意外结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!