你好,在每一段代码之前,我描述了下面的问题。提前谢谢!!
我从MySQL数据库读取X,Y坐标。我现在使用3个文件: coordinate_array、db_conn和map.php
连接:
<?php
//declaring connection
$db_user = "u";
$db_pwd = "p";
$db_server = "v";
$db_name = "sandbox";
//1. connection to the database
$conn = mysqli_connect($db_server, $db_user, $db_pwd);
//check connection
if(!$conn){
die("Database connection failed: " . mysqli_error());
}else{
echo "connected to MySQL<br>";
}
// 2. Select a database to use
$db_select = mysqli_select_db($conn, $db_name);
if (!$db_select) {
die("Database selection failed: " . mysqli_error());
}
mysqli_close($conn);
?> 在coordinate_array:中,我正在创建一个多维数组,这样我就可以绘制所有由我的查询获取的矩形,然后使用json_encode($desk)。我忽略了表中的coordinate_id,因为我只需要Javascript部分的x,y值。
<?php
$select_coordinate_query = "SELECT * FROM coordinates";// WHERE coordinate_id ='1'
$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
while($row = mysqli_fetch_assoc($result)){
//get desk array count
$desk = array( array("x" => $row['x_coord']),
array("y" =>
$row['y_coord'])
);
// Frame JSON
// Return the x, y JSON here
echo json_encode($desk);
} //end while loop
?> 在map.php中:我试图通过使用JQuery来获得这些价值。我想要得到值并运行一个循环,它将执行我的画图函数,该函数将继续为表中的每一行绘制矩形。我对JSON和JQuery非常陌生,并开始使用它。
<div class="section_a" >
<p>Section A</p>
<canvas id="imageView" width="600"
height="500"></canvas>
<script type="text/javascript">
$(document).ready(function(){
/* call the php that has the php array which is json_encoded */
$.getJSON('coordinate_array.php', function(data) {
/* data will hold the php array as a javascript object */
if(data != null){
$.parseJSON(data);
$(data).each(Paint(x,y)){
//get values from json
//for every row run the functionpaint by passing X,Y coordinate
});//end getJson
}//end if
}); //end rdy func
});//end 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>
</div> <!-- end div section_a --> 此外,当包含jquery文件时,我是否有正确的语法。它和我使用的所有其他文件一样。
我的另一个问题是:在每个文件中包含连接文件并在结束时关闭它,还是将连接打开在我已经建立连接的文件中?
提前谢谢,非常感谢!
发布于 2014-11-12 06:44:03
在PHP文件中,您将为while循环中的每个MySQL行输出JSON。您可能希望构建一个大对象并在结束时全部输出一次。
//array that will have number of desks in map area
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);
exit;这将使您在处理JS中的数据时获得成功。
https://stackoverflow.com/questions/26126850
复制相似问题