将JSON数组提取到fullcalenar中

时间:2016-03-13 13:52:34

标签: jquery fullcalendar

我正在尝试将约会从MySQL添加到fullcalendar,但仍然不能。这是我的PHP代码:

修改

(function ($) { 
                $(document).ready(function() {

                  $('#calendar').fullCalendar({
                      eventSources: [

                        // your event source
                        {
                            url: 'fullcalendar/get-events.php',
                            error: function() {
                                alert('there was an error while fetching events!');
                            },
                            color: 'yellow',   // a non-ajax option
                            textColor: 'black' // a non-ajax option
                        }

                        // any other sources...

                    ]
                });

              });
            })(jQuery);

-     

//Include connection file
require_once('global.php');

//Json and PHP header
header('Content-Type: application/json');
$events = array();
$user = $_SESSION['username'];
$id_logged = $_SESSION['login_id'];

    $search_date = "SELECT * FROM appointment INNER JOIN patient ON appointment.patient_id = patient.id WHERE appointment.id_logged = :id_logged";
    $search_date_stmt = $conn->prepare($search_date);
    $search_date_stmt->bindValue(':id_logged', $id_logged);
    $search_date_stmt->execute();
    $search_date_stmt_fetch = $search_date_stmt->fetchAll();

    foreach($search_date_stmt_fetch as $row)
    {
        $events[] = array(
       'title' => $row['patient_name'],
       'start'   => $row['date_app'],
       'end'    => $row['date_app']),
       'allDay' => false;
    }

    echo json_encode($events);
?>

这是fullcalendar脚本:

    <script>
        (function ($) { 
            $(document).ready(function() {
              $('#calendar').fullCalendar({
                  header: {
                      left: 'prev,next today',
                      center: 'title',
                      right: 'month,agendaWeek,agendaDay'
                  },
                  editable: true,
                  eventLimit: true, // allow "more" link when too many events
                  events: {
                      url: 'fullcalendar/get-events.php',
                      //url: 'fullcalendar/myfeed.php',
                  },
                  loading: function(bool) {
                      $('#loading').toggle(bool);
                  }
              });

          });
        })(jQuery);
    </script>

以下是控制台结果:

enter image description here

所以我收到了数据。但是在查询字符串参数中,我有一个起始值和结束值,我不知道它们是什么,并且无法在我的日历中看到任何内容。

enter image description here

我希望我能得到一些帮助。我从昨天起就开始研究它并且无法获得任何结果。

3 个答案:

答案 0 :(得分:1)

首先,将日历源设置为PHP源:

$('#calendar').fullCalendar({
        theme: true,
        lang: 'es',            
        timezone: 'UTC',
        editable: true,
        selectable: true,
        events: '../calendar.php'
 });

日历会发送如下请求: http://localhost/calendar.php?start=2016-02-01&end=2016-03-14&_=1457633346896

现在填写PHP文件:

<?php
header( "Access-Control-Allow-Origin: *");  
header( 'Expires: Sat, 26 Jul 1997 05:00:00 GMT' ); 
header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' ); 
header( 'Cache-Control: no-store, no-cache, must-revalidate' ); 
header( 'Cache-Control: post-check=0, pre-check=0', false ); 
header( 'Pragma: no-cache' ); 

date_default_timezone_set("UTC");    // Set the default timezone
$response = null;

if (isset($_GET["start"]) && isset($_GET["end"]) ) {   
    //--Esta es la consulta principal del calendario:
    $GLOBALS['response'] = GetCalendar($_GET["start"], $_GET["end"] ) ;
} 

header('Content-Type: application/json');
echo json_encode($GLOBALS['response'], true);//<- Response always in JSON format.
echo PHP_EOL;
//============================================================================
function GetCalendar($Start, $End) {
   //start=2016-02-29 end=2016-04-11           
   $response = null;
   $conn = null;

   try {
      $odbc_name = 'myODBCname';

      $sql_query = "SELECT id_event, tipo, descripcion, fecha_inicio, NVL(fecha_fin, MDY(1,1,1)) fecha_fin, 
                    NVL(back_color,'') back_color, NVL(text_color,'') text_color, id_usuario, desc_usuario
                    FROM webapps_calendar
                    WHERE fecha_inicio BETWEEN '".$Start."' AND '".$End."'
                    OR fecha_fin BETWEEN '".$Start."' AND '".$End."' 
                    ORDER BY 1;";

      $conn = odbc_connect($odbc_name, 'user', 'password');
      $result = odbc_exec($conn, $sql_query);
      $response = array();     

       if($result) {
            $response = array();
            while( $row = odbc_fetch_array($result) ) { 
                if ($row['tipo'] == 'evento') {
                    //--Aqui van los Eventos normales ingresados por los usuarios --*/
                    $json['id'] = $row['id_event'];
                    $json['title'] = utf8_encode($row['descripcion']);    
                    $json['start'] = (new DateTime($row['fecha_inicio']))->modify("+12 hours")->format('Y-m-d H:i:s');                        
                    $json['end'] = (new DateTime($row['fecha_fin']))->modify("+12 hours")->format('Y-m-d H:i:s');

                    $json['allDay'] = false;
                    $json['timezone'] = 'UTC';

                    if($row['back_color'] != ''){ $json['color'] = $row['back_color']; } else { $json['color'] = null; }               
                    if($row['text_color'] != ''){ $json['textColor'] = $row['text_color']; } else { $json['textColor'] = null; }    

                    $json['usuario'] = $row['desc_usuario'];
                    $json['user_id'] = $row['id_usuario'];
                    $json['overlap'] = null;
                    $json['rendering'] = null; 
                    $json['type'] = 'Evento';

                    array_push($response, $json); 

                } else {
                    //-- Este es un Dia Feriado -*/
                    $json['id'] = $row['id_event'];
                    $json['title'] = utf8_encode($row['descripcion']);

                    $json['start'] = (new DateTime($row['fecha_inicio']))->modify("+12 hours")->format('Y-m-d H:i:s');

                    if($row['fecha_fin'] != '0001-01-01') {                        
                        $json['end'] = (new DateTime($row['fecha_fin']))->modify("+12 hours")->format('Y-m-d H:i:s');
                    } else { 
                        $json['end'] = null; 
                    } 
                    $json['allDay'] = true;

                    $json['color'] = '#ff9f89';
                    $json['textColor'] = null;
                    $json['rendering'] = 'background';   
                    $json['overlap'] = true;
                    $json['type'] = 'Feriado';

                    array_push($response, $json); 
                }          

            }  

            //Libera recursos y cierra la conexion
            odbc_free_result($result);
        }

   } catch (Exception $e) {
       $response = array('resultado' => 'err', 'detalle' => $e->getMessage());
       echo 'ERROR: ',  $e->getMessage(), "\n";
   }
   odbc_close($conn);
   return $response;
}
?>

PHP源将使用ODBC连接查询数据库并返回常规事件和国家庆祝活动,我还为每个事件添加了几个自定义属性。

祝你好运!

答案 1 :(得分:0)

尝试使用方法eventSources而不是事件,示例:

 eventSources: [

    // your event source
    {
        url: '/myfeed.php', // use the `url` property
        color: 'yellow',    // an option!
        textColor: 'black'  // an option!
    }

    // any other sources...

]

更多信息:http://fullcalendar.io/docs/event_data/events_json_feed/

答案 2 :(得分:0)

也许是构建事件数组的问题

我的样本:

$a_event = array();
$a_event['title'] = $title;
$a_event['url'] = $href;
$a_event['start'] = date('Y-m-d',$date_start);
array_push($a_events_json, $a_event);

在你的捕获中,json似乎不对,我没有看到“开始”字段

也许你的问题就在这一行。

start'   => $row['date_app'],