简体   繁体   中英

FullCalendar.js won't display JSON events from an array

My ASP.NET application produces events and, for now, simply stores them in an HTML list, like so:

<ul id="eventsList">
  <li>
    {editable:false,id:1,title:"Demo",start:"2018-03-14T00:00:00"}
  </li>
</ul>

I convert this list into an array using javascript, like so:

var events = [];

$("#eventsList").find('li').each(function () {
  events.push(this.innerText);
});

$('#eventCalendar').fullCalendar({
  height: "parent",
  events: events
});

FullCalendar, however, does not display any events - despite the event being in an array as described here: https://fullcalendar.io/docs/events-array

What am I missing here?

First, when you push the event data using innerText , like this:

$("#eventsList").find('li').each(function () {
  events.push(this.innerText);
});

It's actually pushing a string and not an object of an event expected by Fullcalendar.

To get around this, you can use JSON.parse function to parse a JSON string into an object. But the problem is, from your explanation above, the event data within the <li> tag is not properly quoted.

{editable:false,id:1,title:"Demo",start:"2018-03-14T00:00:00"}

To be a valid JSON string, the property name like editable , id , title and start , must be properly quoted. To get around this, you can use replace and some regex to put the quotes around the property name:

var properJSONString = eventString.replace(/([a-z]+):/g, '"$1":')

So, to wrap this up you can push the events from the <li> tag like this:

$(document).ready(function () {
  var events = [];

  // Loop through each list.
  $("#eventsList li").each(function () {
    // Get the event data, which is a string.
    var eventString = $(this).text().trim();
    // Properly quote the key (property name), so it's a valid JSON string.
    var jsonString = eventString.replace(/([a-z]+):/g, '"$1":');

    // Parse it to object with JSON.parse() and push it to events variable.
    events.push(JSON.parse(jsonString));
  });

  $('#calendar').fullCalendar({
    height: "parent",
    events: events
  });
});

You may check the demo here: hopeful-franklin-085848.bitballoon.com

However, it's not a clean solution. FullCalendar already offers a feature to load events directly from your server. Read more about it here: events (as JSON Feed) .

Hope this gives you some ideas.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM