2014-09-30 15 views
0

你好,我在每段代碼之前描述了下面的問題。提前致謝!!從PHP到JQuery和運行功能的JSON值

我正在閱讀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的那些價值。我想獲取這些值並運行一個 循環,該循環將執行我的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的文件時,我..其在相同 ,我使用所有其他文件。

另一個問題我有是:這是很好的,包括在每一個文件的連接文件,並在年底 關閉或保持連接在我的文件打開,我havethe建立連接?

非常感謝!

回答

0

在您的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中處理這些數據。