2016-10-17 92 views
0

我正在使用FullCalendar插件。我想顯示保存在數據庫表中的事件,有沒有辦法選擇和顯示這些?PHP日曆 - 從PHP獲取事件

的Javascript:

$(document).ready(function() { 
    $('#calendar').fullCalendar({ 
     defaultDate: '2016-09-12', 
     editable: true, 
     eventLimit: true, // allow "more" link when too many events 
     events: [ 
      { 
       id: 999, 
       title: 'Test Event', 
       start: '2016-09-09', 
       end: '2016-09-11' 
      } 
+0

建立與您的JSON元素來自你的SQL查詢的結果。 – chris85

+0

不知道該怎麼做,你有鏈接教程或例子,你可以回答? – Shane

+1

看看:http://stackoverflow.com/questions/6281963/how-to-build-a-json-array-from-mysql-database不要使用那裏使用的'mysql_ *'函數,那答案是5歲,使用PDO或mysqli。 – chris85

回答

2

有你需要做相當多的東西,下面的方法真的只有一小一次性的項目,它不會很好地進行縮放。它將概述您需要採取的基本步驟。

你需要寫一個簡單的服務,接受選定日期的查詢字符串PARAM。

服務應該使用類似PDO的東西來從數據庫中的數據包含查詢。

我建議從這裏開始: https://phpdelusions.net/pdo

基本可以用準備好的聲明中安全使用日期值作爲選擇標準。

然後你會使用數組構造你的響應。在這個例子中,關聯數組有一個名爲「data」的鍵,其中包含一個帶有兩個鍵「name」和「value」的關聯數組的索引數組。

然後,您的標題設置爲「內容類型:應用程序/ json'so瀏覽器知道如何處理的響應。

最後,您希望使用json_encode函數將嵌套數據數組處理爲JSON。

最裸露的骨頭的服務應該是這樣的:

<?php 
date_default_timezone_set('UTC');//Set time zone appropriately 
//Get date from url , I set a default if there is no date, you mat want to throw an error... 

//Error throw if data param missing! 
$myDate = $_GET['date']; 

//Query DB to get back a result set. The sample data below is allows you to get a JSON respons back. 
//check out this tutorial to get a good understanding of how to use PDO to get your data from the DB: https://phpdelusions.net/pdo 

//This represents the data from your query. 
$foo = Array(
    data => Array(
     Array(
      'name' => 'Bar', 
      'value' => 42, 
      ), 
      Array(
      'name' => 'Baz', 
      'value' => -42, 
      ) 
     ) 
); 

//Make sure you set the header and then echo the content, there should be no extra white space after the header is set! 
header('Content-Type: application/json'); 
echo json_encode($foo); 
?> 

假設這是位於foo.com/get-events.php,以下請求:

$.ajax({ 
    url: 'http://foo.com/get-events.php', 
    method: 'GET', 
    dataType: 'json' 
}) 
.done(function(data) { 
//Use data to set calendar!!! 
console.log('Data: ', data); 
}); 

將輸出跟隨JSON:

{"data":[{"name":"Bar","value":42},{"name":"Baz","value":-42}]} 

此外,這裏是一個簡單的結構化項目,促進代碼重用和覆蓋是上面概述的主題。它的好的部分,你可能可以複製/粘貼和改變,以滿足您的需求

- Getting/Setting data using PDO

- A simple service that handles the data from the DB

- JSON response helper Class

- DB/Table Info and setup

+1

應該有開始時間和結束時間是可選的; – itzmukeshy7