【问题标题】:JQuery DatePicker Unavailable Dates via PHP Json通过 PHP Json 的 JQuery DatePicker 不可用日期
【发布时间】:2016-03-26 15:38:10
【问题描述】:

我正在尝试从 MySQL 数据库中检索日期,该数据库将用于在 datepicker UI 中动态禁用日期。我已从数据库中检索日期并将其编码为 JSON。这是回显 JSON 的输出:

[
 {"dates":"21-03-2016"},
 {"dates":"31-03-2016"},
 {"dates":"31-03-2016"},
 {"dates":"30-03-2016"}
 ] 

我已尝试将 JSON 获取到将被检索并用于消除日期的 javascript 页面。但是,它无法正常工作,因为日期选择器 UI 甚至不再出现。

有什么建议吗?谢谢。

checkDates.php

<?php
$servername = "localhost";
$username = "user";
$password = "user";
$dbname = "ebooking";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
 } 

$sql = "select booking_date from booking";
$result = $conn->query($sql);

$checkDates = array();

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $checkDate['dates'] = $row['booking_date'];
       
        $checkDates[] = $checkDate;
    }
} else {
    echo "0 results";
}
echo json_encode($checkDates);
 $conn->close();
 ?> 
 

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    <link rel="stylesheet"
          href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <link rel="stylesheet" href="/resources/demos/style.css">

    <script>
        $(function() {
            $( "#datepicker" ).datepicker({
                dateFormat: 'dd-mm-yy',
                beforeShowDay: checkAvailability

            });
        })
        
        $.getJSON('checkDates.php?dld='+ id, function(json){dates=json;});

        function checkAvailability(mydate){
            var myBadDates = dates;

            var $return=true;
            var $returnclass ="available";
            $checkdate = $.datepicker.formatDate('dd-mm-yy', mydate);

            // start loop
            for(var x in myBadDates)
            {
                $myBadDates = new Array( myBadDates[x]['start']);

                for(var i = 0; i < $myBadDates.length; i++)
                    if($myBadDates[i] == $checkdate)
                    {
                        $return = false;
                        $returnclass= "unavailable";
                    }
            }
            //end loop

            return [$return,$returnclass];
        }
    </script>
</head>
<body>
Date:
<input type="text" id="datepicker">
</body>
</html>

【问题讨论】:

  • 您是否在索引文件中混合了 Jquery 和 php?
  • @Torchify 在我的索引文件中,我同时使用 jquery 和 php。
  • checkdates.php 中的 mime 类型必须设置为 application/json。不确定您是否这样做,因为整个文件不存在。尝试:header('Content-Type: application/json'); 另外,在您的 checkAvailability javascript 函数中,“日期”变量来自哪里?它没有在 $.getJSON 行中分配。
  • 更具体地说,$.getJSON 行中dates 的范围不是全局的。您应该在函数外部声明 dates 以便在全局范围内使用它。靠近脚本顶部的标签:var dates;。您还应该重命名您的 javascript 变量而不使用 $,因为它非常令人困惑。
  • @Torchify 我对如何实施您的建议感到很困惑。你能纠正我的代码吗?

标签: javascript php jquery json datepicker


【解决方案1】:

好的,所以我稍微修改了你的 javascript,这是我想出的代码:

$(function() {
  //ajax call better placed here.
  id="my ID"; //Define id, as it's not defined in the original post.
  /* Commented out just for JsFiddle, uncomment this for live version.
  $.getJSON('checkDates.php?dld=' + id, function(json) {
    dates = json;


    $("#datepicker").datepicker({
      dateFormat: 'dd-mm-yy',
      beforeShowDay: checkAvailability

    });
  });
  */
  //For JsFiddle ONLY remove this section of code for live version.
  dates = [{
    "dates": "21-03-2016"
  }, {
    "dates": "31-03-2016"
  }, {
    "dates": "31-03-2016"
  }, {
    "dates": "30-03-2016"
  }];
  $("#datepicker").datepicker({
    dateFormat: 'dd-mm-yy',
    beforeShowDay: checkAvailability

  });
  //End for JsFiddle
});




function checkAvailability(mydate) {


  var myBadDates = dates;

  var $return = true;
  var $returnclass = "available";
  $checkdate = $.datepicker.formatDate('dd-mm-yy', mydate);


  // start loop


  for (var x in myBadDates) {

    if (myBadDates[x].dates == $checkdate) {
      $return = false;
      $returnclass = "unavailable";
    }



  } //end loop



  return [$return, $returnclass];
}

请参阅 jsFiddle: https://jsfiddle.net/gregborbonus/v1dwqq5r/1/

如果 ajax 失败,那么它将中断。

我已经编辑了代码,更新后的 jsFiddle 在这里: https://jsfiddle.net/gregborbonus/v1dwqq5r/2/

您的 php 可能会吐出一些不同的东西,如果这对您不起作用,请链接到您的 php 脚本,我可以测试正确的标头并测试 ajax 调用本身,但我怀疑这甚至是问题。

【讨论】:

  • 使用静态变量,它可以工作,但是当我尝试实现 JSON 时,单击文本框时不会出现 datepicker UI。
  • @abcdefg 如果您为我的解决方案编辑了 php,则需要将其放回 Greg 的原始嵌套数组。
  • @GregBorbonus 我刚刚实现了您的第二个版本,并且确实出现了日期选择器 UI,但日期仍然可用。据我了解,在 php 文件和 JavaScript 文件之间传输 JSON 是否存在问题? php文件的位置会影响这个吗?
  • 这是 ajax url 本身的问题。您应该能够使用检查器查看错误的来源。
  • 是的,位置确实会影响这一点。因此,假设 index.jsp 在您网站的根目录中:/index.jsp,然后您将 checkDates.php 文件放在同一目录中,那么您的所有 js 脚本都应该指向 /checkDates.php(注意 /) .现在,如果您想将它放在另一个文件夹中,那么您可以: /folder/checkDates.php 为您的 js,然后您将 checkDates.php 移动到名为文件夹的文件夹中。
【解决方案2】:

检查日期.php

<?php
//Set document mime type... this is important since you want to return json not text!
header('Content-Type: application/json');

$servername = "localhost";
$username = "user";
$password = "user";
$dbname = "ebooking";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
 } 

$sql = "select booking_date from booking";
$result = $conn->query($sql);

$checkDates = array();

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $checkDates[] = $row['booking_date'];
    }
} else {
    echo "0 results";
}
echo json_encode($checkDates);
$conn->close();
?>

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    <link rel="stylesheet"
          href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <link rel="stylesheet" href="/resources/demos/style.css">


</head>
<body>
Date:
<input type="text" id="datepicker">
</body>
<script>
    var badDates;
    $.getJSON('checkDates.php, function(json){badDates=json;});

    $(function() {
        $( "#datepicker" ).datepicker({
            dateFormat: 'dd-mm-yy',
            beforeShowDay: function(date) {
                if($.inArray($.datepicker.formatDate('dd-mm-yy', date ), badDates) > -1)
                {
                    return [false,"Unavailable","Booked"];
                }
                else
                {
                    return [true,"Available","Not Booked"];
                }
            }
        });
    })

</script>
</html>

试试这个。我将内容类型添加到 php 文件中。我还稍微改变了javascript。

为 php 文件中的平面数组编辑,感谢@Greg_Borbonus

【讨论】:

  • 代码不错,很干净。唯一的问题是 php 代码是这样的:` $checkDate['dates'] = $row['booking_date']; $checkDates[] = $checkDate;` 这会将数组 $checkDate 作为数组 $checkDates 上的新元素。为了让你的 js 代码工作,你需要一个一维数组,这个 php 代码创建一个二维数组。
  • @Torchify 谢谢你的建议。我已经实施了您的建议,但不可用的日期没有显示为灰色。我应该将 PHP 文件放在文件夹结构中的什么位置?是否将其放在 Web Content 文件夹中?
  • 我在@GregBorbonus fiddle 的一个分支中检查了我的代码,它可以工作。 (见这里:jsfiddle.net/qo74smpz)你能检查 chrome devtools 中的 xhm 返回并查看 php 返回的内容吗?否则,您可以实施 Greg 的解决方案。
  • @Torchify 使用静态日期,它的工作原理和它应该如何工作完全相同。但是当我取消注释实时版本并摆脱静态日期时,所有日期都在 UI 上可用。
  • @abcdefg 你能测试你的php文件的返回吗?请准确发布返回的内容。您可以在 chrome devtools 或同等工具中检查这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-04
  • 1970-01-01
  • 2011-03-16
  • 2010-12-19
  • 2020-02-15
相关资源
最近更新 更多