如何正确使用 JSON 将 Events/EventSources 传递给 FullCalendar?

How do I use JSON properly to pass Events/EventSources to FullCalendar?

我的最终目标是通过 JSON 动态传递 eventSources。在我什至开始动态生成 JSON 内容之前,我尝试使用文档示例通过 JSON URL 将一个简单的单个事件传递到我的事件标签中,手动编写。

我可以看到 URL 有效,因为我可以通过 php 在我的 wordpress 网站上回显结果,但是我传递的 JS 脚本 JSON URL 只是让日历崩溃。这个我真的很头疼。

还提到 prev/next 按钮触发 GET 到 JSON 与本地时区日期(比如当前显示月份的范围)。我应该如何语法 json 以便让事件调用找到数据点范围?我只是对这一切感到困惑。

JSON 文件:calendar.json


{
    "title" : "something",
    "start" : "2019-04-23"  
}

PHP 文件:页面-calendar.php

<?php
    //Wordpress function for URL to the file location
    $url = get_stylesheet_directory_uri() . '/calendar.json'; 
    $data = file_get_contents($url);
    $content = json_decode($data);

    echo $content->title; // Just to test if the URL works 
    echo $content->start; // This echos just fine

    ?>
<html lang='en'>
      <head>
        <meta charset='utf-8' />
        <script>
          document.addEventListener('DOMContentLoaded', function() {
            var calendarEl = document.getElementById('calendar');

            var calendar = new FullCalendar.Calendar(calendarEl, {
              plugins: [ 'dayGrid' ],

              events: $url;
            });

            calendar.render();
          });
        </script>
      </head>
      <body>
        <div id='calendar'></div>
      </body>
</html>

我不太确定,如果这可以解决您的问题,我也不了解 WordPress。但是,也许您可​​以尝试使用 WordPress 内置函数,也许在这种情况下,您可以尝试 wp_remote_get 或找到类似的函数来代替 file_get_content()。因为,也许出于安全或许可的原因,您不能从某些 URL 获取内容,不确定。

您可以使用 chmod($url, 0000); 进行测试,看看是否允许您更改文件的权限。然后,如果这是一个权限问题,您可以将 chmod() 添加到您的脚本中:

//Wordpress function for URL to the file location
$url = get_stylesheet_directory_uri() . '/calendar.json';
chmod($url, 0777);
//$data = file_get_contents($url);
$data = wp_remote_get($url);
$content = json_decode($data);
chmod($url, 0755);

echo $content->title;
echo $content->start;

您的 PHP 代码似乎没问题。也许,var_dump($url); 以确保一切正常。

此外,您可以尝试更改

events: $url;

events: <?php echo $url; ?>

JSON 需要是一组事件(即使该数组只包含一个对象)。目前您只有一个对象,fullCalendar 不会读取它。

使您的 calendar.json 文件看起来像这样:

[
  {
    "title" : "something",
    "start" : "2019-04-23"  
  }
]

您还需要稍微更改代码,以便您的 PHP $url 变量被视为 PHP 并呈现,并且输出也被视为JS 的字符串,而不是按原样注入 JS:

events: "<?php echo $url; ?>"

如果您的 php 和完整日历在同一页面上,您可能需要这个

<?php
   $url = get_stylesheet_directory_uri() . '/calendar.json';
?>

<html lang='en'>
  <head>
    <meta charset='utf-8' />
    <script>
      document.addEventListener('DOMContentLoaded', function() {
        var calendarEl = document.getElementById('calendar');

        var calendar = new FullCalendar.Calendar(calendarEl, {
          plugins: [ 'dayGrid' ],

          events: "<?php echo $url; ?>";
        });

        calendar.render();
      });
    </script>
  </head>
  <body>
    <div id='calendar'></div>
  </body>
</html>

记得检查 calendar.json 的输出。 应该是这样的

            [
             {
              "title" : "something",
              "start" : "2019-04-23"  
             }
            ];