将PHP数组返回到Javascript数组

Sir*_*iss 0 javascript php arrays ajax canvas

我试图将我的SQL查询数组返回到一个javascript数组,然后一次显示一个信息.我已经在这里发现了一些有用的帖子,但我仍然无法让它工作.我是ajax的新手,所以请原谅任何愚蠢的错误.下面是php后面的描述.php:这是来自index.php的外部文件

<?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;
?>
Run Code Online (Sandbox Code Playgroud)

这将获得结果(它们是文件路径)数组,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>
Run Code Online (Sandbox Code Playgroud)

我希望这是有道理的.再次感谢!

Thi*_*ter 7

用于json_encode()将其编码为JSON.在最近的浏览器中,您可以简单地将该函数中的字符串转换为JavaScript对象var obj = JSON.parse(yourstring);- 但最好使用例如jQuery for AJAX和JSON解析.

更新:您的JavaScript应该像这样循环来迭代查询中的数据:

$.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;
    });
});
Run Code Online (Sandbox Code Playgroud)

但是,它可能无法达到您想要的效果:它会在同一位置同时绘制所有图像.

同样替换<script>imageload() </script>(假设是包含JavaScript的函数),<script type="text/javascript">imageload();</script>因为它是正确/正确的语法.

在你的PHP代码中你必须替换return $paths;,echo $paths;除非你使用一些依赖于你的文件返回一些东西的框架.另外,发送JSON标头最好:header('Content-type: application/json');

PS:SELECT *结合使用MYSQL_NUM是BadThing.它依赖于表中具有特定顺序的列.如果你只需要一列使用"SELECT columnName"; 如果你需要全部,用于MYSQL_ASSOC获得一个关联数组.