简体   繁体   English

通过ajax发送fetchAll数组

[英]Send fetchAll array via ajax

I have this method that retrieves a list of dates from my database. 我有这种方法可以从数据库中检索日期列表。

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

And I have a model file "load calendar.php" which calls the method getdate: 我有一个模型文件“ load calendar.php”,它调用方法getdate:

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

I want to be able to store the array $dates in an array my js file: 我希望能够将数组$ dates存储在我的js文件的数组中:

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

          }

      }); 

However, when I alert dbdates, nothing comes out. 但是,当我警告dbdates时,什么也没有发生。 My 'getdate' method works. 我的“ getdate”方法有效。 I only need help with the Ajax call. 我只需要有关Ajax调用的帮助。 Thank you in advance! 先感谢您!

Analyze these statements here, 在这里分析这些陈述,

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

getdate() method actually returns an array, and what you're trying to do with echo $dates; getdate()方法实际上返回一个数组,以及您要对echo $dates; is, you're trying to convert an array to a string, which won't work. 是,您正在尝试将数组转换为字符串,这将不起作用。

Instead, json_encode the array and echo it, like this: 相反, json_encode数组并echo它,如下所示:

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

Also, add dataType: 'json' setting in your AJAX request, like this: 此外,在您的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);
        }

    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM