我有一个PHP函数,我在其中传递一个变量,它返回一个包含开始日期和结束日期的数组。
<?php
function dateRangeTimeFrame($var1){
...
$date['startDate'] = $startDate;
$date['endDate'] = $endDate;
return $date;
}
?>
我还试图在AJAX调用中使用这个PHP函数,这样我就可以重用代码了。我已经把这个添加到页面的开头:
if (isset($_POST['dateFunction'])) {
print_r(dateRangeTimeFrame($_POST['dateFunction']));
}
我的jQuery代码如下:
$.ajax({
url: 'includes/functions.php',
type: 'post',
data: { "dateFunction": theDate},
success: function(response) {
console.log(response['startDate']);
console.log(response.startDate);
}
});
我的问题是,我不知道如何访问php函数返回的响应。
以下是我从PHP函数得到的响应:
Array
(
[startDate] => 2015/01/17
[endDate] => 2015/02/16
)
如何从PHP响应中获取这2个变量?
您需要使用JSON。您的Javascript能够理解并解析
if (isset($_POST['dateFunction'])) {
echo json_encode(dateRangeTimeFrame($_POST['dateFunction']));
}
你的jQuery(注意我添加了dataType
)
$.ajax({
url: 'includes/functions.php',
dataType: 'json',
type: 'post',
data: { "dateFunction": theDate},
success: function(response) {
console.log(response.startDate);
}
});
<?php
function dateRangeTimeFrame($var1){
...
$date['startDate'] = $startDate;
$date['endDate'] = $endDate;
return json_encode($date);
}
?>
jQuery
$.ajax({
url: 'includes/functions.php',
type: 'post',
data: { "dateFunction": theDate},
dataType: "json",
success: function(response) {
console.log(response.startDate);
}
});
<?php
function dateRangeTimeFrame($var1) {
// ...
$date['startDate'] = $startDate;
$date['endDate'] = $endDate;
echo json_encode($date);
}
?>
Ajax
$.ajax({
url: 'includes/functions.php',
type: 'post',
data: { "dateFunction": theDate },
success: function(response) {
for (var i = 0; i < response.length; i++) {
alert(response[i].startDate);
}
}
});