【问题标题】:Saving dates from DatePicker in cookies and sending date to Datatable将 DatePicker 中的日期保存在 cookie 中并将日期发送到 Datatable
【发布时间】:2020-04-27 10:36:46
【问题描述】:

由于我的开发人员不可用,我正在尝试在我的项目中使用我的一点 JQuery 知识来取得进展,但我面临着一个障碍。我正在尝试创建一个 cookie,它将用户选择的日期范围保存在 datepicker 中,并在用户刷新或返回页面时使报告在数据表中可用。

我现在所做的只是在选择日期时创建/刷新 cookie,并在用户返回时在 datepicker 上重新选择日期范围,但由于未发送 Ajax 请求,因此不会刷新这些日期的报告到数据表。

到目前为止,这是我的代码:

$('#demo').daterangepicker({
    "timePicker24Hour": true,
    "autoApply": true,
    ranges: {
        'Today': [moment(), moment()],
        'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
        'Last 7 Days': [moment().subtract(6, 'days'), moment()],
        'Last 30 Days': [moment().subtract(29, 'days'), moment()],
        'This Month': [moment().startOf('month'), moment().endOf('month')],
        'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
    },
    "alwaysShowCalendars": true,
    "startDate": Cookies.get('startdate'),
    "endDate": Cookies.get('enddate'),
    "opens": "left",
    }, function(start, end, label) {
        $("#datereturn").text(start.format('MMMM D, YYYY') + ' to ' + end.format('MMMM D, YYYY'));
        var todaydate = start.format('YYYY-MM-DD')+"to"+end.format('YYYY-MM-DD');
        Cookies.set('startdate', start.format('MM/DD/YYYY'));
        Cookies.set('enddate', end.format('MM/DD/YYYY'));
        $.ajax({
            url:"campaign-table.php",
            method:"POST",
            data:{todaydate:todaydate},
            success:function(data){
                $('#campaigntable').html(data);
            }
        });
});

我需要在页面加载时执行代码末尾的 Ajax 请求。我尝试了下面的代码,但它似乎不起作用。 Shorty,如果不存在,它会在页面加载时创建 cookie,否则它会将 Ajax 请求发送到数据表,其中包含来自 cookie 的日期以显示报告:

$(function(){
    var d = new Date();
    var month = d.getMonth()+1;
    var day = d.getDate();

    var output = 
        ((''+month).length<2 ? '0' : '') + month + '/' +
        ((''+day).length<2 ? '0' : '') + day  + '/'
        + d.getFullYear() ;

    if (Cookies.get('startdate')  == null || Cookies.get('enddate') == null) {
          Cookies.set('startdate', output);
          Cookies.set('enddate', output);
    }

    if (Cookies.get('startdate') && Cookies.get('enddate')) {
        var todaydate = Cookies.get('startdate')+"to"+Cookies.get('enddate');
        $.ajax({
            url:"campaign-table.php",
            method:"POST",
            data:{todaydate:todaydate},
            success:function(data){
                $('#campaigntable').html(data);
            }
        });
    }
});

编辑:我认为我没有在适当的地方进行更改。我有这段代码,正是campaign-table.php 应该加载的地方。

$(document).ready(function(){
    var todaydate = (new Date()).toISOString().split('T')[0]+"to"+(new Date()).toISOString().split('T')[0];
    $.ajax({
        url:"campaign-table.php",
        method:"POST",
        data:{todaydate:todaydate},
        success:function(data){
            $('#campaigntable').html(data);
        }
    });
});

$('li.dropdown.mega-dropdown').on('click', function (event) {
    $(this).parent().toggleClass('open');
});

$('body').on('click', function (e) {
    if (!$('li.dropdown.mega-dropdown').is(e.target) 
        && $('li.dropdown.mega-dropdown').has(e.target).length === 0 
        && $('.open').has(e.target).length === 0) {
        $('li.dropdown.mega-dropdown').removeClass('open');
    }
});

【问题讨论】:

  • 你有 2 个 if 语句尝试将第二个语句更改为 else 语句。
  • 不幸的是它没有用
  • PHP 脚本campaign-table.php todaydate 期望范围值是2020-04-15to2020-04-24,这是正确的吗?
  • 没错。我已经编辑了我的问题,因为我可能试图以错误的代码将日期范围发送到表格。见文末代码。

标签: javascript jquery cookies


【解决方案1】:

如果我正确理解了这个问题,您是否需要与用户选择页面加载日期时相同的功能?这意味着:

  • 检查我们是否已有用于现有开始/结束日期的 cookie;
  • 如果存在,请使用它们;如果不使用一些默认值(今天?);
  • 使用这些日期触发 AJAX 请求;
  • 使用来自 AJAX 的响应更新数据表;

为此,我只需要更改一些小东西:

1) daterangepicker 当前使用现有的 cookie 来设置开始/结束日期。但这将在用户第一次访问该页面时失败,因为这些 cookie 尚不存在。最好在这里测试并设置一些默认值来处理这种情况。

2) 您希望在页面加载时运行的 AJAX 与您希望在用户选择日期时运行的 AJAX 完全相同。因此,我会将其提取到一个通用函数中,您可以在每个需要它的地方引用它,以避免重复代码。

$(document).ready(function(){
    // Create a simple function to fire the AJAX using the date you specify,
    // and show the response on the page.  We can reference this whenever we
    // need to do that.
    function showReport(todaydate) {
        $.ajax({
            url:"campaign-table.php",
            method:"POST",
            data:{todaydate:todaydate},
            success:function(data){
                $('#campaigntable').html(data);
            }
        });
    }

    // Check if we have cookies with dates, if not, set them to defaults
    // (today for both).  Now when the date range picker uses the
    // cookies the very first time a user visits, it will work.
    if (Cookies.get('startdate') == null || Cookies.get('enddate') == null) {
        Cookies.set('startdate', (new Date()).toISOString().split('T')[0]);
        Cookies.set('enddate', (new Date()).toISOString().split('T')[0]);
    }

    var todaydate = Cookies.get('startdate') + "to" + Cookies.get('enddate');

    // We have our dates, fire off the AJAX, and display the response.
    // This runs on page load, as you need.
    showReport(todaydate);

    // Now initialise the date range picker
    $('#demo').daterangepicker({
        // ... all your options, unchanged ...
    }, function(start, end, label) {
        $("#datereturn").text(start.format('MMMM D, YYYY') + ' to ' + end.format('MMMM D, YYYY'));
        var todaydate = start.format('YYYY-MM-DD')+"to"+end.format('YYYY-MM-DD');
        Cookies.set('startdate', start.format('MM/DD/YYYY'));
        Cookies.set('enddate', end.format('MM/DD/YYYY'));

        // Fire off the AJAX with the selected dates and show the response.
        showReport(todaydate);
    });
});

您不需要以$(function(){ 开头的问题中引用的代码,我们刚刚添加到$(document).ready(function(){ 的内容现在可以处理。

【讨论】:

  • 首先感谢您的回答。我按照你的指示做了,但似乎有问题,因为 DatePicker 中的日子现在被 NaN 取代。 function(start, end, label) 之后的说明不清楚。我只添加了以 $("#datereturn") 开头的行和之后的行。对吗?
  • @CreekBarbara 我已经更新了我的答案中的function(start, end, label) 部分以使其更清晰 - 您问题中代码的唯一更改是删除$.ajax({ ... }); 部分,并添加调用到我们的新函数来实际执行 AJAX 部分:showReport(todaydate);。如果仍然有问题,请检查浏览器的开发控制台,看看是否报告了任何错误。
  • 我做的和你的代码完全一样。我还有NaN。这是我在控制台中看到的错误“错误: 属性转换:预期数字,“缩放(NaN)翻译”。当我选择自定义愤怒时,日期会返回,当我刷新日期时会预先选择,但是报告未加载。
  • 编辑:我更改了 set.cookie 日期格式,不再遇到 Nan 问题,但是使用 cookie 日期时报告仍然无法加载
  • 我想通了。我不得不在我的问题中更改第三个代码中的日期,因为这是加载页面时发生的调用报告的地方。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-25
  • 2021-11-24
  • 2012-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多