2014-09-30 26 views
0

我讀X,從MySQL數據庫Y座標。JSON數組值在JQuery的使用和執行功能

2檔,假裝連接有:coordinate_array和map.php

更新這裏在coordinate_array:我想提出一個多維數組這樣我就可以再使用json_encode($臺)。我只需要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 

>

上面的代碼給我此:

[[{ 「×」: 「20」},{ 「Y」: 「20」}],[ { 「×」: 「30」},{ 「Y」: 「30」}],[{ 「×」: 「40」},{ 「Y」: 「40」}],[{ 「×」:」 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> 

預先感謝您它是非常感謝!

+0

在你的'getJson'調用加入這一行'的console.log(數據);'和後輸出。 – Hackerman 2014-09-30 18:03:58

+0

我沒有輸出? – mario 2014-09-30 18:07:41

+0

在你的Javascript控制檯(Chrome中的F12)...那裏你應該能夠看到輸出... – Hackerman 2014-09-30 18:08:49

回答

1

你正在做的JSON錯誤。它應該在您的數據庫讀取循環完成後進行編碼。既然你在做循環內的編碼,你吐出多個獨立的JSON編碼的字符串,這將被視爲在接收端有語法錯誤。

例如

while($something) { 
    echo json_encode($some_array); 
} 

會吐出卡住靠在彼此

[something][something][something] 

三個單獨的JSON編碼陣列。你需要的是更多的東西是這樣的:

while($something) { 
    build_array(); 
} 
echo json_encode($array); 

這將吐出

[something,something,soemthing] 

代替。

+0

我剛剛嘗試了您的建議,並最終以此結尾:[{「x」:「20」},{「y」:「20」}] [{「x」:「30」},{「y」 :「30」}] [{「x」:「40」},{「y」:「40」}] [{「x」:「50」},{「y」:「50」}] ..只有表格中的最後一個座標:[{「x」:「50」},{「y」:「50」}] .. – mario 2014-09-30 18:22:51

+0

'while($ row = mysqli_fetch){$ arr [] = $ row ; }回聲json_encode($ arr);' – 2014-09-30 18:30:35

+0

謝謝數組的工作。我怎麼會忽略coordinate_id,因爲我只想把X,Y用於JQuery? – mario 2014-09-30 18:38:59

0

嘗試使用 報頭( '內容類型:應用程序/ JSON'); 在coordinate_array.php

+0

我做了什麼,這會有幫助嗎? – mario 2014-09-30 18:29:59

+0

你會得到正確的標題。 – Darius 2014-09-30 18:39:47