我正在从 MySQL 数据库读取 X,Y 坐标。
2 个文件,假装存在连接:cocod_array 和 map.php
在此处更新 在cocod_array中:我正在制作一个多维数组,这样我就可以使用json_encode($desk)。我只需要 Javascript 部分的 x,y 值。
<?php
include 'db_conn.php';
header('Content-Type: application/json');
$select_coordinate_query = "SELECT x_coord, y_coord FROM coordinates";
$result = mysqli_query($conn,$select_coordinate_query);
//see if query is good
if($result === false) {
die(mysqli_error());
}
//array that will have number of desks in map area
$desk = array(); // just added
while($row = mysqli_fetch_assoc($result)){
//get desk array count
$desk[] = array( array("x" => $row['x_coord']),
array("y" => $row['y_coord'])
);
} //end while loop
echo json_encode($desk); //encode array
?>
上面的代码给了我这个:
[[{"x":"20"},{"y":"20"}],[{"x":"30"},{"y":"30"}],[{ "x":"40"},{"y":"40"}],[{"x":"50"},{"y":"50"}]]
在map.php中:我试图使用JQuery获取这些值。我想获取这些值并运行一个循环来执行我的 Paint 函数,该函数将为表中的每一行绘制矩形。我对 JSON 和 JQuery 很陌生,并开始使用它。
<canvas id="imageView" width="600" height="500"></canvas>
<script type="text/javascript">
请在此寻求帮助
//I have no idea how to get the encoded values
$(document).ready(function(){
$.getJSON('coordinate_array.php', function(data)){
$.each(data, function(k,v){
Paint(v[0].x, v[1].y);
});//end each
});//end get json
});//end rdy func
我想执行此功能
//function to paint rectangles
function Paint(x,y)
{
var ctx, cv;
cv = document.getElementById('imageView');
ctx = cv.getContext('2d');
ctx.lineWidth = 5;
ctx.strokeStyle = '#000000';
//x-axis,y-axis,x-width,y-width
ctx.strokeRect(x, y, x+100 , y+100);
}
</script>
预先感谢您,非常感谢!
最佳答案
你的 json 格式错误。它应该在数据库获取循环完成后进行编码。由于您是在循环内进行编码,因此会输出多个独立的 JSON 编码字符串,这将在接收端被视为语法错误。
例如
while($something) {
echo json_encode($some_array);
}
会吐出来
[something][something][something]
三个独立的 json 编码数组相互挤压。你想要的是更像这样的东西:
while($something) {
build_array();
}
echo json_encode($array);
会吐出来
[something,something,soemthing]
相反。
关于javascript - 在 JQuery 和执行函数中使用的 JSON 数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26127126/