I am trying to assign a json array to a javascript array so that my JS functions can access the array. So I have an ajax call to MySQL db to get a JSON array of data:
我试图将一个json数组分配给一个javascript数组,以便我的JS函数可以访问该数组。所以我对MySQL db进行了ajax调用以获取JSON数据数组:
var data = [];
$.ajax({
type:"post",
url:"position.php",
dataType:'json',
success:function(jsonarray){
data=$.parseJSON(jsonarray);
}
});
position.php:
position.php:
<?php
include 'dbconnect.php';
$sql = "SELECT pid, posX, posY FROM posTable;";
$result = $conn->query($sql);
$myrows = $result->num_rows;
$return=array();
if ($result->num_rows>0){
while($row=$result->fetch_assoc()){
$return[]=array((int)$row['pid'],(int)$row['posX'],(int)$row['posY']);
}
}else{
echo "[]";
}
echo json_encode($return);
$conn->close();
?>
This gives an output like this:
这给出了这样的输出:
[[1,749,1000],[2,855,986],[3,955,946],[4,1037,934],[5,1111,912]]
And from this I want the following two dimensional array so that I can access its memebers in this form:
从这里我想要以下二维数组,以便我可以以这种形式访问它的成员:
data[i][j]
data => [[1,749,1000],[2,855,986],[3,955,946],[4,1037,934],[5,1111,912]]
However when I execute the code I keep getting the following error:
但是,当我执行代码时,我不断收到以下错误:
Uncaught SyntaxError: Unexpected token , in JSON at position 1
What am I doing wrong?
我究竟做错了什么?
1 个解决方案
#1
2
jQuery will automatically parse a JSON response before populating the success function's first argument.
jQuery将在填充成功函数的第一个参数之前自动解析JSON响应。
$.parseJSON(jsonarray);
calls toString()
on your array and then tries to parse it as JSON, which it isn't (because Array.prototype.toString()
doesn't convert to JSON).
$ .parseJSON(JSONArray),其中,在您的数组上调用toString()然后尝试将其解析为JSON,而不是它(因为Array.prototype.toString()不会转换为JSON)。
Just don't try to parse it again.
只是不要试图再次解析它。
#1
2
jQuery will automatically parse a JSON response before populating the success function's first argument.
jQuery将在填充成功函数的第一个参数之前自动解析JSON响应。
$.parseJSON(jsonarray);
calls toString()
on your array and then tries to parse it as JSON, which it isn't (because Array.prototype.toString()
doesn't convert to JSON).
$ .parseJSON(JSONArray),其中,在您的数组上调用toString()然后尝试将其解析为JSON,而不是它(因为Array.prototype.toString()不会转换为JSON)。
Just don't try to parse it again.
只是不要试图再次解析它。