通过ajax发送fetchAll数组

时间:2016-10-01 21:43:25

标签: javascript php ajax

我有这个方法从我的数据库中检索日期列表。

function getdate($id) {
    $select = $this->db->query("select * from dates where user_id= '$id' ");
    $row = $select->fetchAll(PDO::FETCH_COLUMN);
    return $row;        
}

我有一个模型文件“load calendar.php”,它调用方法getdate:

    $dates = $user->getdate($id);
    echo $dates;

我希望能够将数组$ date存储在我的js文件数组中:

    $(document).ready(function() {
        var dbdates = new Array();
        $.ajax({
             type: 'POST',
             url: 'loadcalendar.php',
             data: { dates:dates },
             success: function(response) {
                 dbdates = response;
                 alert(dbdates);

          }

      }); 

然而,当我提醒dbdates时,没有任何结果。我的'getdate'方法有效。我只需要Ajax调用的帮助。提前谢谢!

1 个答案:

答案 0 :(得分:1)

在此处分析这些陈述,

$dates = $user->getdate($id);
echo $dates;

getdate()方法实际上会返回一个数组,而您尝试对echo $dates;进行的操作是,您正在尝试将数组转换为字符串,这会赢得&#39工作。

相反,json_encode数组和echo,如下所示:

$dates = $user->getdate($id);
echo json_encode($dates);

另外,在AJAX请求中添加dataType: 'json'设置,如下所示:

$(document).ready(function() {
    var dbdates = new Array();
    $.ajax({
        type: 'POST',
        url: 'loadcalendar.php',
        data: { dates:dates },
        dataType: 'json',
        success: function(response) {
            dbdates = response;
            console.log(dbdates);
        }

    });
});
相关问题