jquery 如何循环遍历json数据并在flatpickr上实现

1bqhqjot  于 2023-02-03  发布在  jQuery
关注(0)|答案(5)|浏览(111)

首先,我知道这个问题已经被问到,但我已经尝试了大多数,如果不是所有的解决方案,提供和不能得到它正确的工作。
我在Symfony 3项目中使用flatpickr,我需要能够根据预订的假期禁用某些日期。当从下拉列表中选择某个人时,系统会查询数据库以找出他们是否在任何时间点度假,如果是,则返回这些日期作为“from”和“to”。然后将结果进行JSON编码并通过 AJAX 响应返回。
以下是 AJAX 调用的响应示例:

[{"from":"2017-06-05","to":"2017-06-09"},{"from":"2017-06-27","to":"2017-06-28"}]

flatpickr需要一组日期来禁用,如下所示:

{
    disable: [
        {
            from: "2017-04-01",
            to: "2017-06-01"
        },
        {
            from: "2017-09-01",
            to: "2017-12-01"
        }
    ]
}

因此,我使用了以下jQuery来尝试获得所需的结果:

$.each(response, function(i, dateitem){
        console.log(dateitem.from + " - " + dateitem.to);
});

用于测试目的,但没有显示. response是Controller中数据库的返回结果。
任何人都可以帮助我转换成正确的格式与Flatpickr使用这些数据,因为我挣扎了很多。

cx6n0qe3

cx6n0qe31#

最后我做了很长的路要走,在那里你按顺序陈述每个日期被禁用。
我使用DatePeriod()获取from和to之间的所有日期,然后再次添加end date(因为DatePeriod()不这样做),如下所示:

foreach ($holidays as $row) {
    $start_date = new \DateTime($row->getStartDate()->format('Y-m-d'));
    $end_date = new \DateTime($row->getEndDate()->format('Y-m-d'));
    $date_range = new \DatePeriod($start_date, new \DateInterval('P1D'), $end_date);
    foreach($date_range as $date){
        $date_array[] = $date->format('Y-m-d');
    }
    // Add the end date as this is not included in the date period.
    $date_array[] = $row->getEndDate()->format('Y-m-d');
}

我给 AJAX 输入了一个json编码的结果,然后在ajax上成功了:

var parsed = JSON.parse(response);

var optional_config = {
    enableTime : true,
    disable: parsed
};

这就成功了:)

bn31dyow

bn31dyow2#

这对我来说绝对有效。我没有给你看服务器代码,因为你用的是PHP,而我用的是C#。如果你想要我的服务器代码,请请求。

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index800</title>
    <script src="~/Scripts/jquery-1.12.4.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/flatpickr/2.6.3/flatpickr.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/flatpickr/2.6.3/flatpickr.js"></script>
    <script type="text/javascript">
        $(function () {
            //MAKE SURE TO click on Ok button to fill jsonDateRanges
            var jsonDateRanges;
            $("#btn").click(function (ev) {
                var AjaxDataReceive = { organizationId: $("#ddOrganization").val() };
                $.ajax({
                    type: "POST",
                    url: "/Home/Index800",
                    data: AjaxDataReceive,
                    dataType: "json",
                    success: function (response) {
                        $("#output").val(JSON.stringify(response.AjaxDataSend));
                        jsonDateRanges = response.AjaxDataSend;
                        $("#flatpickrText").flatpickr
                        (
                            {
                                disable: jsonDateRanges

                            }
                        );
                    },
                    error: function (Result) {
                        alert("Error");
                    }
                });
                //var jsonDateRangesWorks = [
                //            {
                //                from: "2017-05-01",
                //                to: "2017-05-03"
                //            },
                //            {
                //                from: "2017-05-10",
                //                to: "2017-05-12"
                //            }
                //]
            })

        })
    </script>
</head>
<body>
    <div>
        <input type="text" value="APDH" id="ddOrganization" />
        <input type="text" id="output" style="width:600px" />
        <input type="text" id="flatpickrText" />
        <input type="button" value="Ok" id="btn" />
    </div>
</body>
</html>
gc0ot86w

gc0ot86w3#

这是我的服务器代码,如果你需要的话。

public class AjaxDataReceive
{
    public string organizationId { get; set; }
}

public class AjaxDataSend
{
    public string from { get; set; }
    public string to { get; set; }
}

public class HomeController : Controller
{
    [HttpPost]
    public ActionResult Index800(AjaxDataReceive ajaxData)
    {
        AjaxDataSend ads = new AjaxDataSend { from = "2017-05-03", 
            to = "2017-05-05" };
        AjaxDataSend ads2 = new AjaxDataSend
        {
            from = "2017-05-10",
            to = "2017-05-12"
        };

        IList<AjaxDataSend> list = new List<AjaxDataSend>();
        list.Add(ads);
        list.Add(ads2);

        return Json(new
        {
            AjaxDataSend = list
        }
                , @"application/json");
    }

    public ActionResult Index800()
    {
        return View();
    }
t5fffqht

t5fffqht4#

我很遗憾它对你不起作用,你需要修改你的服务器代码,这样当你在 AJAX 调用成功时设置一个断点,这个变量看起来像这样:

c9qzyr3d

c9qzyr3d5#

HTML代码

<input class="form-`control form-control-solid flippick" placeholder="Pick event date" type="text" id="kt_datepicker_3"/>

Jquery代码

$(".flippick").flatpickr({
  mode: "range",
  // disable: ["2023-02-01", "2023-02-02", "2023-02-08"],
  disable: ty,
  dateFormat: "Y-m-d",
  onOpen: [
    function(selectedDates, dateStr, instance) {
      $.ajax({
        "url": "<?=base_url("venue/vanueBookedDate"); ?>",
        "type": "post",
        dataType:"Json",
        "data": {
          venueId: vid,
        },
        success: function(data) {
          instance.set('disable', data);
        }
      });
    }]
  });

服务器代码PHP

public function vanueBookedDate() {
  $venueID = $this->input->post('venueId');
    
  $sql = "SELECT * FROM USER_REQUEST WHERE VENUE_ID='$venueID' AND BOOKING_STATUS='CONFIRM'";
  $dataS = $this->unicon->CoreQuery($sql,'result_array');
  $dataArr = [];
  foreach ($dataS as $dataS) {
    $rangeDateS = $this->getDatesFromRange($dataS['EVENT_DATE'],$dataS['TILL_DATE']);
    
    foreach ($rangeDateS as $rangeDate) {
      $dataArr[] = $rangeDate;
    }
  }
  echo json_encode($dataArr);
}

测试代码

相关问题