通过Ajax将数组从Php传输到jQuery

时间:2014-01-11 14:42:07

标签: php jquery ajax arrays

我在外部$array文件中生成日期数组.php,其格式为2014-01-10(这是Jan)。

我想要实现的是将此数组传递给jquery,以便在Ajax成功回调函数中使用。

当我在.php文件中打印数组时,我得到:

Array ( [0] => 2013-12-10 [1] => 2013-12-10 [2] => 2013-12-11 [3] => 2013-12-12 [4] => 2013-12-12 [5] => 2013-12-12 [6] => 2013-12-16 [7] => 2013-12-16 [8] => 2013-12-16 [9] => 2013-12-16 [10] => 2013-12-17 [11] => 2013-12-17 [12] => 2013-12-17 [13] => 2013-12-17 [14] => 2013-12-18 [15] => 2013-12-18 [16] => 2013-12-18 [17] => 2013-12-19 [18] => 2013-12-19 [19] => 2013-12-20 [20] => 2013-12-20 [21] => 2013-12-20 [22] => 2013-12-20 [23] => 2013-12-20 [24] => 2013-12-20 [25] => 2013-12-23 [26] => 2013-12-23 [27] => 2013-12-27 [28] => 2013-12-27 [29] => 2013-12-27 [30] => 2013-12-27 [31] => 2013-12-27 [32] => 2013-12-27 [33] => 2013-12-30 [34] => 2013-12-30 [35] => 2013-12-30 [36] => 2013-12-30 [37] => 2013-12-31 [38] => 2014-01-03 [39] => 2014-01-05 [40] => 2014-01-07 [41] => 2014-01-07 [42] => 2014-01-08 [43] => 2014-01-08 [44] => 2014-01-08 [45] => 2014-01-08 [46] => 2014-01-08 [47] => 2014-01-08 [48] => 2014-01-08 [49] => 2014-01-08 [50] => 2014-01-09 [51] => 2014-01-09 [52] => 2014-01-09 [53] => 2014-01-09 [54] => 2014-01-09 ) 

我尝试的是.php文件:

$tried = implode(",", $array);    
echo $tried;

然后在我的.js文件中使用jQuery:

$(document).ready(function() {    
    $.ajax({
        type: 'POST',
        url: 'php/expire.php',
        data: { expired: true },
        success: function(data) {
            takis = data.split(',');
        }
    });
});

但我的问题是当php文件中的数组为空时takis.length为1,而它应为零。有没有其他方法来传输数组而不会像使用dataType之类的东西那样发生爆炸?或者我做错了什么?

4 个答案:

答案 0 :(得分:2)

试试这个

echo json_encode($array);

现在您应该可以在类似于此

的javascript中作为标准Java脚本对象进行访问
data.0.blah

答案 1 :(得分:2)

试试:

$tried = json_encode($array);

答案 2 :(得分:2)

我用于这种编码的方法是让php在php-sided脚本上通过此命令将变量排列成JSON代码:

$json=json_encode($yourquery);

它将在回调函数中将数组触发到jQuery,并且它将处理JSON字符串。

答案 3 :(得分:2)

在你的php文件中非常简单,你必须有这样的东西:

$array = Array ( '2013-12-10', '2013-12-10', '2013-12-11', '...' );
$array = Array( 'data' => $array );
echo json_encode($arr);

你的javascript脚本必须是这样的:

$(document).ready(function() {

    $.ajax({
    type: 'POST',
    url: 'php/expire.php',
    data: { expired: true },
    success: function(response) {
        takis = response.data;
        console.log( takis ); // show you an array

    }
    });
});