【发布时间】:2014-11-24 05:08:32
【问题描述】:
我更新了我的代码。它有 Javascript、PHP、JSON 和 JQuery。我正在读取 X,Y 坐标 MySQL 数据库。 我现在使用 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)。我忽略了表中的坐标 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 来获得这些价值。我想获取值并运行 循环将执行我的 Paint 函数,该函数将为 桌子。我对 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 文件时,我的语法是否正确。它与 我正在使用的所有其他文件。
我的另一个问题是:在每个文件中都包含连接文件并在最后关闭它是否很好 或者在我建立连接的文件中保持连接打开?
提前感谢您,非常感谢!
【问题讨论】:
-
不是答案,但您提供的代码是无法维护的混乱。考虑至少不要在一个文件中混合 HTML、JS、PHP 和 SQL。
-
您正在为从数据库中提取的每组坐标创建一个新画布。我确定这不是你想要做的。另外,不要使用
mysql_*()- 它已被弃用。使用mysqli_*()获取新代码。 -
注意 MySQL 有 [dev.mysql.com/doc/refman/5.5/en/spatial-datatypes.html](native support) 用于坐标系统数据。你不应该使用
mysql_*()或mysqli_*();而是使用 PDO 或其他一些抽象层。是的,如果您想要一些有用的改进建议,请将您的代码分开。 -
感谢大家的回复,我将研究 PDO 以确保改进此代码,但在此之前我发布了我更新的代码。另外,我知道你们中的一些人说我不应该在 PHP 中包含 JS,那么如果这是我能想到的唯一方法,我还能如何将我的值用于画布?如果你们可以请解释如何将 JS 与 PHP 分开,这将很有帮助。再次感谢
标签: javascript php jquery json mysqli