[英]PHP Calendar - Get events from PHP
我正在使用FullCalendar插件。 我想顯示保存在數據庫表中的事件,是否可以選擇並顯示這些事件?
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'
}
您將需要做很多事情,以下方法實際上僅適用於小型一次性項目,無法很好地擴展。 它將概述您需要采取的基本步驟。
您需要編寫一個簡單的服務,該服務接受所選日期的查詢字符串參數。
服務應包含使用PDO之類的查詢以從數據庫中獲取數據。
我建議從這里開始: https : //phpdelusions.net/pdo
必不可少的是,您可以使用准備好的語句來安全地使用日期值作為選擇標准。
然后,您將使用數組來構造響應。 在此示例中,關聯數組具有一個名為“ data”的鍵,該鍵包含帶有兩個鍵“ name”和“ value”的關聯數組的索引數組。
然后,您將標頭設置為“ Content-Type:應用程序/ json”,以便瀏覽器知道如何處理響應。
最后,您想使用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}]}
這也是一個簡單的結構化項目,可促進代碼重用並涵蓋上面概述的主題。 您可以復制/粘貼和更改其中的大部分內容以滿足您的需求
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.