这是我第一次构建自己的JavaScript代码,所以还没有完全掌握它。
我正在查询MySQL数据库以获取所有禁用日期,以便在日期选择器中禁用结果。我几乎有这个工作,但问题是当从数据库中读取两个时,只有一组值被发布到JavaScript变量。即如果我的数据库中有两个预订,一个来自6/3/15 - 10/3/15,一个来自15/3/15 - 17/3/15,只有一个预订存储在JavaScript变量中。即6/3/15 - 10/3/15。
当我回显json_encode($ date_list)时,我得到的结果为:
["2015-3-14","2015-3-15","2015-3-16","2015-3-17","2015-3-17"]
["2015-3-6","2015-3-7","2015-3-8","2015-3-9","2015-3-10","2015-3-10"]
哪个是正确的,但是当我在scheduledDays变量上执行console.log时,存储的唯一值是:
["2015-3-6", "2015-3-7", "2015-3-8", "2015-3-9", "2015-3-10", "2015-3-10"]
以下是我正在使用的代码。
<?php
$bookeddates = "SELECT fromdate, todate FROM messages WHERE listing_id = '".$_GET['listingid']."'";
$resultbookeddates = mysql_query($bookeddates) or die(mysql_error() . "<br>" . $bookeddates);
while ($rowbookeddates = mysql_fetch_assoc($resultbookeddates)) {
$from = date('Y-n-j', strtotime($rowbookeddates['fromdate']));
$to = date('Y-n-j', strtotime($rowbookeddates['todate']));
$start_time = strtotime($from);
$end_time = strtotime($to);
$date_list = array($from);
$current_time = $start_time;
while($current_time < $end_time) {
//Add one day
$current_time += 86400;
$date_list[] = date('Y-n-j',$current_time);
}
$date_list[] = $to;
?>
<script type="text/javascript">
var bookedDays = <?php echo json_encode($date_list); ?>;
</script>
<?php
echo json_encode($date_list);
} ?>
任何帮助都将不胜感激。
答案 0 :(得分:1)
你需要将你注入的JS移动到你的while循环之外。如评论中所述,首先构建数据,然后输出。
<?php
$bookeddates = "SELECT fromdate, todate FROM messages WHERE listing_id = '".$_GET['listingid']."'";
$resultbookeddates = mysql_query($bookeddates) or die(mysql_error() . "<br>" . $bookeddates);
$date_list = array();
while ($rowbookeddates = mysql_fetch_assoc($resultbookeddates)) {
$from = date('Y-n-j', strtotime($rowbookeddates['fromdate']));
$to = date('Y-n-j', strtotime($rowbookeddates['todate']));
$start_time = strtotime($from);
$end_time = strtotime($to);
$date_list[] = $from;
$current_time = $start_time;
while($current_time < $end_time) {
//Add one day
$current_time += 86400;
$date_list[] = date('Y-n-j',$current_time);
}
$date_list[] = $to;
} ?>
<script type="text/javascript">
var bookedDays = <?php echo json_encode($date_list); ?>;
</script>
<?php
echo json_encode($date_list);
答案 1 :(得分:0)
你的问题是javascript变量的赋值。 请在while循环之外移动作业,你可以看到所有结果。
<?php
$bookeddates = "SELECT fromdate, todate FROM messages WHERE listing_id = '".$_GET['listingid']."'";
$resultbookeddates = mysql_query($bookeddates) or die(mysql_error() . "<br>" . $bookeddates);
while ($rowbookeddates = mysql_fetch_assoc($resultbookeddates)) {
$from = date('Y-n-j', strtotime($rowbookeddates['fromdate']));
$to = date('Y-n-j', strtotime($rowbookeddates['todate']));
$start_time = strtotime($from);
$end_time = strtotime($to);
$date_list = array($from);
$current_time = $start_time;
while($current_time < $end_time) {
//Add one day
$current_time += 86400;
$date_list[] = date('Y-n-j',$current_time);
}
$date_list[] = $to;
} ?>
<script type="text/javascript">
var bookedDays = <?php echo json_encode($date_list); ?>;
</script>