如何从日期选择器 jQuery UI 中检索选定的日期值以触发某些操作

How can I retrieve the selected date value from datepicker jQuery UI in order to trigger something

如标题所述,我想根据 jQuery UI 日期选择器中选定的日期用数据更新我的页面。所以我需要在没有选择日期的情况下检索当前日期值,或者检索所选日期数据并粉碎当前日期值,这样我就可以在页面上动态显示有关所选日期的内容。

到目前为止,这是我的日期选择器代码:

var date_choisie;

$( function() {
    $("#calendrier").datepicker({
        dateFormat: "yy-mm-dd",
        onSelect: function(selectedDate) {
        // console.log(selectedDate); //Selected date
        date_choisie = selectedDate; //My attempt to put selectedDate in date_choisie
        }
    })
    //set date as current by default
    $("#calendrier").datepicker('setDate', new Date());

    //get date in a variable
    date_choisie = $('#calendrier').datepicker('getDate');
    date_choisie = $.datepicker.formatDate("yy-mm-dd", date_choisie);

    // console.log(date_choisie); //2020-09-20
} );

所以我需要能够在 date_choisie 中获得 selectedDate(也许我应该 return selectedDate

之后,我将使用 ajax 将 date_choisie 传递到我的 PHP 文件:

$.ajax({
    method: 'get',
    url : 'http://planning-ilm.atwebpages.com/userPlanning/'+ date_choisie,
    dataType : 'json',
    success: function(data){
        let semaine = document.createTextNode('Sem du ' + data.datecourante.mday + '/' + data.datecourante.mon + '/' + data.datecourante.year);
        $("#sem")[0].appendChild(semaine);
        showplannings(data.datecourante, data.message);
    }
})

URL 将调用以下 php 函数:

 function getUserPlanning($url){
        // Function used to get the user planning
        $today = getdate(); // This is the line i will change with the selected date

        // Searching for monday, if the selected date is not monday
        if($today ['weekday'] !== "Monday"){
            $monday = getdate(strtotime("last Monday")); //This is the line i will change with the selected date
            
            // We get everything in an array
            $dayMonthYear = dayMonthYearOfDate($monday);

            // Concatenation in string
            $dayMonthYearString = $dayMonthYear['day']. ' ' . $dayMonthYear['month']. ' ' . $dayMonthYear['year'];
        
            // We get every day of the week in array
            $theWeek = currentWeek($dayMonthYearString);

            return $error = json_encode([
                'status' => 'ok',
                'datecourante' => $monday, // Here is the monday of the selected day
                'message' => getHisPlanning($url[1], $theWeek)
            ]);
        }else{
            $dayMonthYear = dayMonthYearOfDate($today);
            $dayMonthYearString = $dayMonthYear['day']. ' ' . $dayMonthYear['month']. ' ' . $dayMonthYear['year'];
            // On a la semaine actuelle
            $theWeek = currentWeek($dayMonthYearString);

            
            return $error = json_encode([
                'status' => 'ok',
                'datecourante' => $today, // Here is the monday of the selected day
                'message' => getHisPlanning($url[1], $theWeek)
            ]);
        }
    }

这里是getUserPlanning

中用到的函数
function dayMonthYearOfDate($dateTostring){
        // Fonction permettant de retourner le jour, le mois et l'année sous forme de tableau
        $jour = $dateTostring['mday'];
        $mois = $dateTostring['month'];
        $annee = $dateTostring['year'];

        $dateofDay = ['day' => $jour, 'month' => $mois, 'year' => $annee];
        
        return $dateofDay;
    }
function currentWeek($currentDate){
        // Fonction permettant de retourner tous les jours de la semaine courante en prenant un string
        $monday = strtotime($currentDate);
        $tuesday = strtotime("next Tuesday", strtotime($currentDate));
        $wednesday = strtotime("next Wednesday", strtotime($currentDate));
        $thursday = strtotime("next Thursday", strtotime($currentDate));
        $friday = strtotime("next Friday", strtotime($currentDate));
        $saturday = strtotime("next Saturday", strtotime($currentDate));
        $sunday = strtotime("next Sunday", strtotime($currentDate));

        $week = [$monday, $tuesday, $wednesday, $thursday, $friday, $saturday, $sunday];
        return $week;
    }

通过使用 getUserPlanning,我可以检索在 data.datecourante

中注册的所选日期

您可以将 ajax 调用包装在 function 中,然后 call 每次 select 调用 new 日期。

要在 屏幕上显示 currentselected 日期, 您可以使用 .text 函数显示日期。加载日期页面后,将调用 ajax,当前 date 数据将从 PHP.

fetch

最后,调用 ajax 后,您可以在 success 函数中相应地显示 PHP ajax 数据。

编辑: 你也可以将你的 selecteddate 传递给这个函数 => showplannings(data.datecourante, data.message, selectedDate); 在这个函数中添加第三个 argument 并且在你的 showplannings 函数中接收这个 third 参数并做任何必要的事情。

现场演示:

$(function() {
  $("#calendrier").datepicker({
    dateFormat: "yy-mm-dd",
    onSelect: function(selectedDate) {
      //show selected on screen
      $('.selectedDate').text('Selected Date: ' + selectedDate)

      //call ajax on selected date
      myAjaxCall(selectedDate)
    }
  })
  //set date as current by default
  $("#calendrier").datepicker('setDate', new Date());

  //get date in a variable
  let currentDate = $('#calendrier').datepicker('getDate');
  let currentDateFormat = $.datepicker.formatDate("yy-mm-dd", currentDate);

  //Show date on screen
  $('.selectedDate').text('Selected Date: ' + currentDateFormat)

  //Call ajax on load
  myAjaxCall(currentDateFormat) //pass current date to ajax function
});

//Ajax call
function myAjaxCall(selectedDate) {
  $.ajax({
    method: 'get',
    url: 'http://planning-ilm.atwebpages.com/userPlanning/' + selectedDate,
    dataType: 'json',
    success: function(data) {
      //let semaine = document.createTextNode('Sem du ' + data.datecourante.mday + '/' + data.datecourante.mon + '/' + data.datecourante.year);
      //$("#sem")[0].appendChild(semaine);
      //showplannings(data.datecourante, data.message, selectedDate);
                                                 //....^ - pass selected
    }
  })
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<p>Date: <input type="text" id="calendrier"></p>

<p class="selectedDate"></p>

<button class="callAjax">Click Ajax</button>

这是主函数return成功

   function getUserPlanning($url){
        // Get the user planning
        $today = $url[2];
        $nameOfDay = date('l', strtotime($today));
        // echo $nameOfDay;
        // echo $url[1];

        // If it's not Monday
        if($nameOfDay !== "Monday"){
            // (format : d-m-y)
            $monday = date('d-m-Y', strtotime('previous monday', strtotime($today)));
            // $monday = getdate(strtotime("last Monday"));
            // echo("Monday : ".$monday. " ");
           
        
            //Getting all days in array
            $theWeek = currentWeek($monday);

            return $error = json_encode([
                'status' => 'ok',
                'datecourante' => $monday,
                'message' => getHisPlanning($url[1], $theWeek)
            ]);
        }
        else{
            // If already a monday is selected
            echo("ELSE today : ". $today);
            $theWeek = currentWeek($today);

            
            return $error = json_encode([
                'status' => 'ok',
                'datecourante' => $today,
                'message' => getHisPlanning($url[1], $theWeek)
            ]);
        }
    }

下面的函数在 getUserPlanning 中用于获取数组中的天数

 function currentWeek($currentDate){
        // Get all weekdays in array
        $monday = strtotime($currentDate);
        $tuesday = strtotime("next Tuesday", strtotime($currentDate));
        $wednesday = strtotime("next Wednesday", strtotime($currentDate));
        $thursday = strtotime("next Thursday", strtotime($currentDate));
        $friday = strtotime("next Friday", strtotime($currentDate));
        $saturday = strtotime("next Saturday", strtotime($currentDate));
        $sunday = strtotime("next Sunday", strtotime($currentDate));

        // echo("Mardi".$tuesday);
        // echo("Mercredi".$wednesday);
        $week = [$monday, $tuesday, $wednesday, $thursday, $friday, $saturday, $sunday];
        return $week;
    }

最后一个函数是 data.message 应该 return

    function getHisPlanning($employe, $week){
        // Used to return the planning
        $weekPlanning = array(); 
        $connexion = connexion();
        echo("employé : " . $employe . " ");

        // Retrieving planning of each day for an employee
        for($i = 0; $i < 7; $i++){
            // creating format y-m-d
            // echo($week[$i]);
            $dateCurrent = getdate($week[$i]);
            // echo($dateCurrent);
            $day = $dateCurrent['mday'];
            $month = $dateCurrent['mon'];
            $year = $dateCurrent['year'];

            // used in order to fetch date in db
            $jour = $year. '-' . $month . '-' . $day;
            echo("Jour : " . $jour . " ");

            // $request = $connexion->prepare("SELECT * FROM plannings WHERE id_employe = ? AND date_planning = ? ORDER BY id_plage");
            $request = $connexion->prepare("SELECT * FROM plannings INNER JOIN boutiques ON plannings.id_boutique = boutiques.id_boutique INNER JOIN affectations ON plannings.id_affectation = affectations.id_affectation WHERE id_employe = ? AND date_planning = ? ORDER BY id_plage");
            $request->execute(array($employe, $jour));

            // Stock planning of employee for each day
            $result = $request->fetchAll(PDO::FETCH_ASSOC);

            // Stock planning of week
            array_push($weekPlanning, $result);
        }
        return $weekPlanning;
    }

这是Ajax调用,user是一个id,selectedDate是选择的日期

function AjaxCall(selectedDate, user){
    $.ajax({
        method: 'get',
        url : 'http://planning-ilm.atwebpages.com/userPlanning/'+ user + '/' + selectedDate ,
        dataType : 'json',
        success: function(data){
            // let semaine = document.createTextNode('Sem du ' + data.datecourante.mday + '/' + data.datecourante.mon + '/' + data.datecourante.year);
            // $("#sem")[0].appendChild(semaine);
            showplannings(data.datecourante, data.message);
        }
    })
}

这是节目策划电话会议

$(function() {
  $("#calendrier").datepicker({
    dateFormat: "yy-mm-dd",
    onSelect: function(selectedDate) {
      //show selected on screen
      $('.selectedDate').text('Selected Date: ' + selectedDate)

      //call ajax on selected date
      myAjaxCall(user, selectedDate)
    }
  })
  //set date as current by default
  $("#calendrier").datepicker('setDate', new Date());

  //get date in a variable
  let currentDate = $('#calendrier').datepicker('getDate');
  let currentDateFormat = $.datepicker.formatDate("yy-mm-dd", currentDate);

  //Show date on screen
  $('.selectedDate').text('Selected Date: ' + currentDateFormat)

  //Call ajax on load
  myAjaxCall(user, currentDateFormat) //pass current date to ajax function
});

function myAjaxCall(user, selectedDate) {
  $.ajax({
    method: 'get',
    url: 'http://planning-ilm.atwebpages.com/userPlanning/' + '/' + user + '/' + selectedDate,
    dataType: 'json',
    success: function(data) {
      //let semaine = document.createTextNode('Sem du ' + data.datecourante.mday + '/' + data.datecourante.mon + '/' + data.datecourante.year);
      //$("#sem")[0].appendChild(semaine);
      showplannings(data.datecourante, data.message);
                                                
    }
  })
}