2011-01-12 123 views
0

我想返回我的SQL查詢數組到一個javascript數組,然後一次顯示一個信息。我已經在這裏找到了一些有用的帖子,但我仍然無法實現它的工作。我對阿賈克斯很陌生,所以請原諒任何愚蠢的錯誤。下面是php後面的描述。 PHP:這是在外部文件中的index.php從返回PHP數組到Javascript數組

<?php 
include('connection.php'); 

$query = "SELECT * FROM photos"; 
$queryresult = mysql_query($query); 

while ($line = mysql_fetch_array($result)) { 
    $path[] = $row[0]; 
} 
$paths = json_encode($path); 
header('Content-type: application/json'); 
echo $paths; 
?> 

這得到(它們是文件路徑)陣列和JSON編碼它們來傳遞的JavaScript的結果。 Connection.php是正確的,它正在工作。

HTML/JavaScript的:

<html> 
<head> 
<script src="JavaScript/gjs.js" type="text/javascript"></script> 
<script src="jquery/jquery-1.4.3.min.js" type="text/javascript"></script> 
<script> 
function imageload(){ 
var i = 1; 
$.getJSON('phpfiles/getpiccode.php', function(data) { 

    var can = document.getElementById('canvas').getContext('2d'); 

    $.each(data,function(idx, row){ 
    var img = new Image(); 
    img.onload = function(){ 
     can.drawImage(img, 0, 0, 1280, 800); 
    } 
    img.src = row; 
      i++; 
}); 

}); 

} 
</script> 
</head> 

<body> 
<div class="container"> 
<canvas id="canvas" class="canvas-one" width="1280" height="800"> 
<script>imageload();</script>This text is displayed if your browser does not support HTML5 Canvas</canvas> 
</div> 

</body> 
</html> 

我希望是有道理的。再次感謝!

+0

var newpath =「」;在變更處理程序裏面..真的看起來很糟糕.. – Ben 2011-01-12 00:59:00

+0

我從這個網站上的另一篇文章中得到了。我不知道這是否正確,但已經嘗試了許多其他方法,而且似乎沒有其他方法可行。打開想法。謝謝回覆! – Siriss 2011-01-12 01:26:40

回答

7

使用json_encode()編碼它作爲JSON。 在最近的瀏覽器中,您可以使用var obj = JSON.parse(yourstring);簡單地將該函數的字符串轉換爲JavaScript對象 - 但更好地使用用於AJAX和JSON解析的jQuery。

更新:目前JavaScript應該looke一樣,從你的查詢遍歷數據:

$.getJSON('phpfiles/getpiccode.php', function(data) { 
    // get canvas object. it's the same for all images so only do it once 
    var can = document.getElementById('canvas').getContext('2d'); 
    // iterate over the elements in data 
    $.each(data, function(idx, row) { 
     var img = new Image(); 
     img.onload = function() { 
      can.drawImage(img, 0, 0, 1280, 800); 
     } 
     img.src = row; 
    }); 
}); 

但是,你想要什麼它可能不會做的事:它會在同一幾乎同時提請所有圖片位置。

還用<script type="text/javascript">imageload();</script>代替<script>imageload() </script>(假設這是包含JavaScript的函數),因爲這是正確的/正確的語法。

在您的PHP代碼中,您必須將return $paths;替換爲echo $paths;,除非您使用某個依賴於文件返回內容的框架。此外,它可以發送一個JSON頭:header('Content-type: application/json');

PS:SELECT *MYSQL_NUM相結合是BadThing。它依賴於表格中具有特定順序的列。如果你只需要一列使用「SELECT columnName」;如果您需要全部,請使用MYSQL_ASSOC來獲取關聯數組。