Javascript 从PHP到JQuery和run函数的JSON值

Javascript 从PHP到JQuery和run函数的JSON值,javascript,php,jquery,mysql,json,Javascript,Php,Jquery,Mysql,Json,您好,在每段代码之前,我在下面描述了我遇到的以下问题。提前谢谢 我正在从MySQL数据库读取X,Y坐标。 我现在使用3个文件:坐标数组、db\u conn和map.php 连接: 在坐标数组中:我正在制作一个多维数组,这样我就可以画出所有正在绘制的矩形 通过查询获取,然后使用json_encode$desk。我忽略了表中的坐标id 因为我只需要Javascript部分的x,y值 <?php $select_coordinate_query = "SELECT * FROM coordi

您好,在每段代码之前,我在下面描述了我遇到的以下问题。提前谢谢

我正在从MySQL数据库读取X,Y坐标。 我现在使用3个文件:坐标数组、db\u conn和map.php

连接:

在坐标数组中:我正在制作一个多维数组,这样我就可以画出所有正在绘制的矩形 通过查询获取,然后使用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获得这些值。我想得到这些值并运行一个 循环,它将执行my 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文件时,我是否有正确的语法。。它和 我正在使用的所有其他文件

我的另一个问题是:在每个文件中包含连接文件并在最后关闭它是否好 或者在我建立连接的文件中保持连接打开


提前谢谢,非常感谢

在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中处理这些数据时获得成功

 //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;