-1

我想使用 jquery datepicker 来选择一个日期,然后在选择它时根据所选日期从数据库中选择查询我已经寻找并找到了这个问题 jQuery datepicker with php and mysql 他们说我应该使用 ajax 来做它,但我无法理解他们所做的实现!任何人都可以帮助我尝试做类似的事情

    <script>

$(function() {

    $( "#datepicker" ).datepicker({minDate: 0, showAnim: "bounce",
     onSelect: function(dateText, inst) {<?php mysql_select_db($database_conn, $conn);
$query_time = "SELECT reservation.R_time FROM reservation WHERE reservation.R_date='"?>dateText<?php "'" ;
$time = mysql_query($query_time, $conn) or die(mysql_error());</script>
4

2 回答 2

0

更改您的 JS 以在 onSelect 中发送 ajax 调用,传递dateText.

$( "#datepicker" ).datepicker({
    minDate: 0, 
    showAnim: "bounce",
    onSelect: function(dateText, inst) {
        $.ajax({
            type: 'POST',
            url: 'select_time.php',
            data: {date : dateText},
            success: function(resp){
                if(false !== resp){
                    alert(resp);
                }
            }
        });
    }
});

然后在select_time.php

<?php
    if(!empty($_POST['date'])):
        $mysqli = new mysqli('connection info'); //mysqli connection
        $stmt= $mysqli->prepare('SELECT reservation.R_time FROM reservation WHERE reservation.R_date = ?'); //prepare the statement
        $stmt->bind_param('s', $_POST['date']); //bind our parameters
        $stmt->execute(); //execute our query
        $stmt->store_result(); // store result so we can check rows
        $stmt->bind_result($resTime); //we only want the reserveration time
        $stmt->fetch(); //fetch the rows
        if($stmt->num_rows() > 0):
            echo $resTime;  //return the time from the database
            $stmt->close(); //close the statement
        else:
            return false; //row doesn't exist, return false
        endif;
    endif;    
?>

这是未经测试的,但我看不出它不应该工作的任何原因。

于 2013-04-24T18:55:42.093 回答
-1

我认为你混淆了几件事:

首先,PHP 将始终在页面加载之前运行(因此 jQuery 也是如此),因此在 jQuery 选择器上调用 PHP 将永远不会起作用。

您需要做的是创建一个将在 jQuery 的 onSelect 上触发的 ajax 函数(如果它是一个弹出日历,我通常使用 onClose 事件)。

Javascript:

$( "#datepicker" ).datepicker({
minDate: 0, 
showAnim: "bounce",
onClose: function(dateText, inst) {
   $.post('select_time.php?dateText=' + dateText, function(queryResult){
         // do something with the return query
   });
}
});

PHP页面:

$connection = mysqli_connect("localhost","username","password","db");

$sql = "SELECT reservation.R_time FROM reservation WHERE reservation.R_date={$_post['dateText']}";

if ($result = mysqli_query($connection , $sql))
  {
     while ($getData = mysqli_fetch_field($result))
       {
          echo $getData->R_time;
       }
     mysqli_free_result($result);
  }

mysqli_close($connection);
于 2013-04-24T18:40:17.667 回答