将 Ajax 数组插入日期范围选取器



我已经从社区得到了很多关于这个项目的帮助,但我需要更多的帮助。我有一个Javascript日期范围选择器,我需要从MySQL数据库插入Ajax数组,但由于某种原因它不起作用。这是我的代码:

文件 #1 获取日期范围选择器.php

<?php
include 'dbconfig.php';
$sql="SELECT start_date, end_date FROM date_ranges ";
$result = mysqli_query($conn,$sql);
// Create empty array.
$date_ranges = array();
// Add every row to array;
while($row = mysqli_fetch_array($result)) {
// Create an associative array to store the values in.
// This will later be a JavaScript Object.
array_push($date_ranges, array(
'start'   => $row['start_date'],
'end'     => $row['end_date']
));
mysqli_close($conn);
} 
// Send the $date_ranges as JSON.
$json = json_encode($date_ranges); // '[{"start": "2019-08-18", "end": "2019-08-19"}]'
echo $json;
?>

文件 2 索引.php:

// AJAX request wrapper function.
// Call this function to get the dates from the server.
function getDateRanges(callback) {
$.ajax({
url: 'getdaterangepicker.php',       // Change this to the uri of your file
method: 'GET',                 // Use the GET method
dataType: 'html',              // Expect a JSON response
success: function(response) {  // What will happen when the request succeeds
if (response) {            // Check if there is a response
callback(response);    // Pass the response into the callback
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus + ': ' + errorThrown);
}
});
}
getDateRanges(function(dates) {
$('input[name="start_date"]').daterangepicker({
autoUpdateInput: false,
locale: {
cancelLabel: 'Clear'
},
isInvalidDate: function(date) {
// Here use your dates that you've got from the server.
var dateRanges = [dates];
console.log(dates);
return dateRanges.reduce(function(bool, range) {
return bool || (date >= moment(range.start) && date <= moment(range.end)); 
}, false);
}
});
$('input[name="start_date"]').on('apply.daterangepicker', function(ev, picker) {
document.getElementById("start_date").value = picker.startDate.format('MM/DD/YYYY');
document.getElementById("end_date").value = picker.endDate.format('MM/DD/YYYY');
});
$('input[name="datefilter"]').on('cancel.daterangepicker', function(ev, picker) {
$(this).val('');
});
});

它应该可以工作,javascript 控制台输出正确的数组 ([{"start":"2019-08-20","end":"2019-08-25"}](,但它自己的日期选择器不会划掉无效日期,但是如果我进入代码并将var dateRanges = [dates];替换为var dateRanges = [{"start": "2019-08-25", "end": "2019-08-31"}];它就可以完美地工作,正如预期的那样。什么给?有什么想法吗?日期范围选择器来自此处:http://www.daterangepicker.com

你有几个问题。最主要的是 ajax 请求上的dataTypehtml,而它应该json。因为它是html的,所以dates最终变成了一个字符串。更正后,dates将根据需要成为一个数组,然后您可以直接将其分配给dateRanges,而无需添加嵌套级别,即

var dateRanges = dates;

最新更新