2016-10-01 74 views
0

我有这种方法从我的数据库中检索日期列表。通过ajax发送fetchAll阵列

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

而且我有一个调用该方法GETDATE模型文件“负荷calendar.php”:

$dates = $user->getdate($id); 
    echo $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); 

      } 

     }); 

但是,当我警告dbdates时,什么都不出来。我的'getdate'方法有效。我只需要Ajax调用的帮助。先谢谢你!

+0

您应该打印'response'到控制台,而不是在您尝试将其保存到阵列后使用警报。在使用这些数据之前,你需要确保你得到了回应。 – Jecoms

+0

您应该检查'$ dates'数组是否包含带有'print_r'的数据。要发送数据,请考虑使用'json_encode'(使用PHP)和'JSON.parse(response)'(使用JS) – Alex

+0

仔细检查您是否通过浏览器的“网络”选项卡获取API的响应。此外,尝试和'console.log'的响应,而不是提醒他们。您可以使用'$ .parseJSON'将返回的字符串响应转换为JSON对象。 –

回答

1

这里分析这些语句,

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

getdate()方法实际上返回一个数组,你想用echo $dates;做什么,你想数组转换为字符串,从而赢得”工作。

相反,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); 
     } 

    }); 
}); 
+0

谢谢!有效 。我现在得到这样一个数组:Array ( [0] => 09-23-2016 [1] => 09-20-2016 [2] => 09-21-2016)你知道怎么做我可以将它转换为一串字符串['09 -23-2016','09-20-2016 ...] –

+0

@ S.Al哦,我评论过早了。是的,你可以使用'toString()'方法做到这一点,就像这样:'new Array(dbdates.toString())' –