使用jquery(ajax)和php的上一个和下一个日期

时间:2015-02-26 16:52:30

标签: php jquery mysql ajax

我有一些用PHP编写的日历,带有上一个和下一个按钮。现在我想使用一些ajax转到上一个或下一个日期而不刷新页面。

在ajax调用的php文件中,我有一个查询,它返回选定日期的任务(类似于:...WHERE date = $date)。

问题在于我无法到达今天前一天等等,以及今天的后一天等等。

有人可以提供帮助吗?

修改

按钮:

<button class='btn btn-default previous' data-date='$date'>
  <span class='glyphicon glyphicon-arrow-left' aria-hidden='true'></span>   
</button>
<button class='btn btn-default next' data-date='$date'>
  <span class='glyphicon glyphicon-arrow-right' aria-hidden='true'></span>
</button>

Jquery的:

$(document).ready(function() {
    $('button.previous').click(function() {
        var date = $(this).data('date');
        $.ajax({
            type: "POST",
            data: { action : "previous" , date: date },
            url: "includes/ajax/plannerdata.php",               
            success: function(returnData){                    
                $("#planner-data").html(returnData);
            }
        });
    });
    $('button.next').click(function() {
    var date = $(this).data('date');
        $.ajax({
            type: "POST",
            data: { action: 'next', date: date },
            url: "includes/ajax/plannerdata.php",               
            success: function(returnData){                    
                $("#planner-data").html(returnData); 
            }
        });
    });
});

plannerdata.php:

switch ($_POST['action']) {
    case 'next':
        $date = strftime('%Y-%m-%d', strtotime($_POST['date'] .' -1 day'));
        break;
    case 'previous':
        $date = strftime('%Y-%m-%d', strtotime($_POST['date'] .' +1 day'));
        break;
}

然后我在查询中使用$ date。

UPDATED plannerdata.php:

if (!isset ($_POST['date'])) { // At first page load or refresh (without using the previous/next buttons), plannerdata.php is also loaded bij ajax and injected in index.php
    $currentDatetime = new DateTime('NOW');
}
else { // Previous or next button is pressed
    $currentDatetime = new DateTime($_POST['date']);
}

    $dateModification = $_POST['action'];

    switch ($dateModification) {
        case 'previous':
            $currentDatetime->modify('-1 day');
            break;
        case 'next':
            $currentDatetime->modify('+1 day');
            break;
    }
    $date = $currentDatetime->format('Y-m-d');

修改

plannerdata.php;

if (!isset ($_SESSION['date'])) {
    $_SESSION['date'] = new DateTime('NOW');
}

if (isset ($_POST['action'])) {
    switch ($_POST['action']) {
        case 'previous':
            $_SESSION['date']->modify('-1 day');
            break;
        case 'next':
            $_SESSION['date']->modify('+1 day');
            break;
    }
}

$date = $_SESSION['date']->format('Y-m-d');

按钮(在index.php中)。我删除了data-date属性:

<button class='btn btn-default previous'><span class='glyphicon glyphicon-arrow-left' aria-hidden='true'></span></button>
<button class='btn btn-default next'><span class='glyphicon glyphicon-arrow-right' aria-hidden='true'></span></button>

按钮位于两个按钮内部,并显示所选日期。

<ul>
    <li>button previous</li>
    <li><span id="planner_date">selected date</span></li>
    <li>button next</li>
<ul>

我也改变了Jquery。我同时进行ajax通话。

$(document).ready(function() {
    $('button.previous').click(function() {
        $.when(
                $.post("includes/ajax/plannerdata.php", {action: 'previous'}, function(data) {
                    plannerData = data;
                }),
                $.post("includes/ajax/date.php", {action: 'previous'}, function(date) {
                    calendardate = date;
                })
        ).then(function() {
            $("#planner-data").html(plannerData);
            $("#planner_date").text(calendardate);
        });
    });
    $('button.next').click(function() {
        $.when(
                $.post("includes/ajax/plannerdata.php", {action: 'next'}, function(data) {
                    plannerData = data;
                }),
                $.post("includes/ajax/date.php", {action: 'next'}, function(date) {
                    calendardate = date;
                })
        ).then(function() {
            $("#planner-data").html(plannerData);
            $("#planner_date").text(calendardate);
        });
    });
});

返回当前日期的Date.php:

if (!isset ($_SESSION['current_date'])) {
    $_SESSION['current_date'] = new DateTime('NOW');
}

if (isset ($_POST['action'])) {
    switch ($_POST['action']) {
        case 'previous':
            $_SESSION['current_date']->modify('-1 day');
            break;
        case 'next':
            $_SESSION['current_date']->modify('+1 day');
            break;
    }
}

$date = $_SESSION['current_date']->format('Y-m-d');
echo $date;

编辑2015-03-05:

Jquery的:

$(document).ready(function() {
    $('button.previous').click(function() {
        $.when(
            $.post("includes/ajax/date.php", 
                {action: 'previous'}, 
                function(date) {
                   dates = jQuery.parseJSON(date);
                   calendardate = dates.dutch;

                    $.post("includes/ajax/plannerdata.php", 
                        {date: dates.sql},
                        function(data) {
                            plannerData = data;
                        })
                    })
                    ).then(function(){
                $("#planner_date").text(calendardate);
                $("#planner-data").html(plannerData);
            });
        });
});

date.php

if (!isset ($_SESSION['current_date'])) {
    $_SESSION['current_date'] = new DateTime('NOW');
}
if (isset ($_POST['action'])) {
    switch ($_POST['action']) {
        case 'previous':
            $_SESSION['current_date']->modify('-1 day');
            break;
        case 'next':
            $_SESSION['current_date']->modify('+1 day');
            break;
    }
}
$date_1 = $_SESSION['current_date']->format('Y-m-d');
$date_2 = $_SESSION['current_date']->format('d-m-Y');
$response = array('sql' => $date_1, 'dutch' => $date_2);
echo json_encode($response);

更新2015-03-08

$(document).ready(function() {
    $('button.previous').click(function() {
        var calendardate;
        var plannerData;
        $.when(
            $.post("includes/ajax/date.php", 
                {action: 'previous'}, 
                function(date) {
                   dates = jQuery.parseJSON(date)
                   calendardate = dates.dutch;

                    $.post("includes/ajax/plannerdata.php", 
                            {date: dates.sql},
                            function(data) {
                               plannerData = data;
                            })}
                        )).then(function(){
                $("#planner_date").text(calendardate)
                $("#planner-data").html(plannerData);
            });
        });
});

2 个答案:

答案 0 :(得分:1)

我可以看到,最适合您应该使用PHP DateTime。您可以将脚本修改为以下内容:

$dateModification=$_POST['action'];//for clarification
//Datetime understands every format strtotime does
$currentDatetime=new DateTime($_POST['date']);

switch ($dateModification) {
    case 'next':
        $currentDateTime->modify("+1 day");//simple, isn't it?
        break;
    case 'previous':
        $currentDateTime->modify("-1 day");
        break;
}
//final result
$date=$currentDateTime->format("Y-m-d");

使用DateTime,您可以轻松地将日期作为对象进行操作。也可以将两个Datetime对象与&lt; &GT; ==标志一样简单:

$firstDatetime=new Datetime("2015-02-20");
$secondDatetime=new Datetime("2015-02-25");
if ($firstDatetime<$secondDatetime)
{
    echo '$firstDatetime was indeed first!';
}

自己尝试一下:)

编辑 - 如何在服务器端处理日期修改:

关于它的更多想法。您更新的代码正在对服务器进行两次AJAX调用,它们都在修改日期时间对象。因为它可以工作,它是重复的代码。让我们尝试修改调用和脚本以仅处理一个DateTime对象。我们将日期修改移至您的date.phpplannerdata.php将使用相同的日期变量。

<强>使用Javascript:

$(document).ready(function() {
    $('button.previous').click(function() {
        $.post("includes/ajax/date.php", 
            {action: 'previous'}, 
            function(date) {
                dates = jQuery.parseJSON(date)
                $("#planner_date").text(dates.dutch)
                $.post("includes/ajax/plannerdata.php", 
                    {date: dates.sql},
                    function(data) {
                        $("#planner-data").html(data);
                    })
            })
    })
});

<强> PHP:

Date.php将保持不变,我们必须更改plannerdata.php以使用相同的变量:

//we remove that block, as it will be set in date.php
/*if (!isset ($_SESSION['date'])) {
    $_SESSION['date'] = new DateTime('NOW');
}

if (isset ($_POST['action'])) {
    switch ($_POST['action']) {
        case 'previous':
            $_SESSION['date']->modify('-1 day');
            break;
        case 'next':
            $_SESSION['date']->modify('+1 day');
            break;
    }
}*/

$date = $_SESSION['current_date']->format('Y-m-d');

那应该是它! :)

如何从特定格式创建DateTime?:

出于此目的,存在函数DateTime::createFromFormat。用法示例:

setlocale(LC_TIME, "nl_NL");//firstly we need to setlocale, so month names will be properly recognized
$dateString='6 maart 2015';
$datetime=DateTime::createFromFormat("j F Y", $dateString);

这将返回datetime对象,您可以对其进行操作。

答案 1 :(得分:0)

使用INTERVAL,例如:

TOMORROW:

SELECT * FROM table WHERE date = $date + INTERVAL 1 DAY

YESTERDAY

SELECT * FROM table WHERE date = $date - INTERVAL 1 DAY