【发布时间】: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