[英]JSON.parse unexpected token multidimensional array
Hello I have simple question. 您好,我有一个简单的问题。 I have some data fetched from database and json encoded and sent to html file over AJAX from PHP script.
我有一些从数据库中获取的数据和json编码,并通过PHP脚本通过AJAX发送到html文件。 I want to JSON parse that data.
我想用JSON解析该数据。 Data looks like this:
数据如下所示:
And in PHP file like this: 并在这样的PHP文件中:
$profesors = array
(
'id' => ($id),
'name' => ($profesor)
);
When I try to JSON parse it with JSON.parse() command I get "unexpected token {". 当我尝试使用JSON.parse()命令进行JSON解析时,出现“意外令牌{”。 Does anyone have some suggestion what to do?
有人建议做什么吗? Also if it would be easier for achieving my goal I can use some other data type than array I am using, if someone knows better way...
另外,如果有人更清楚地实现目标,那么我可以使用除数组以外的其他数据类型...
EDIT 编辑
my PHP code that generates 2d array 我的PHP代码生成二维数组
<?php
$var=$_POST["oblast"];
$connection = mysql_connect('localhost','root','pass');
if (!$connection) {die("not successfull" . mysql_error());}
$result = mysql_query('set character set utf8', $connection);
$result = mysql_query('set names utf8', $connection);
$db_select = mysql_select_db("fakultet",$connection);
$brojac=0;
$profesor="";
//$data = array(array());
$queryData = mysql_query("SELECT * FROM predmet WHERE idpred = '$var'");
while($result1 = mysql_fetch_array($queryData))
{
$prof=$result1['idprof'];
$queryData1 = mysql_query("SELECT * FROM profesori WHERE idprof = '$prof'");
while($result2 = mysql_fetch_array($queryData1))
{
$id=$result2['idprof'];
$profesor=$result2['ime']." ".$result2['prezime'];
$profesors = array
(
'id' => ($id),
'name' => ($profesor)
);
echo json_encode($profesors);
}
//echo($result1['idprof']);
//$data[]=$result['idprof'];
}
//echo "$data";
?>
The unexpected token is the second opening curly brace. 意外的标记是第二个花括号。 It's expecting one object because there are no array brackets.
期望有一个对象,因为没有数组括号。 Either have your response look like this:
您的回复如下所示:
[{
"id" : "1",
"name" : "Ivan Nikolaj"
},
{
"id" : "2",
"name" : "Zdravko Topic"
}]
or this : 或这个 :
{
"id" : "1",
"name" : "Ivan Nikolaj"
}
or even better, this: 甚至更好:
{
"status" : 200,
"response" : [
{
"id" : 1,
"name" : "Ivan Nikolaj"
},
{
"id" : 2,
"name" : "Zdravko Topic"
}
]
}
You are doing echo json_encode($profesors);
您正在做
echo json_encode($profesors);
inside your while
loop. 在您的
while
循环中。 Don't do that. 不要那样做 You should only ever call
json_encode
once . 您应该只调用一次
json_encode
。
Try something like this: 尝试这样的事情:
$profesors = array();
while($result2 = mysql_fetch_array($queryData1))
{
$id=$result2['idprof'];
$profesor=$result2['ime']." ".$result2['prezime'];
$profesors[] = array(
'id' => $id,
'name' => $profesor
);
}
echo json_encode($profesors);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.