我有一个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响应中获得这两个vars?
发布于 2015-02-17 04:12:26
您需要使用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);
}
});发布于 2015-02-17 04:17:27
<?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);
}
});发布于 2015-02-17 04:40:50
<?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);
}
}
});https://stackoverflow.com/questions/28554503
复制相似问题