从javascript

时间:2016-05-26 11:11:16

标签: javascript jquery json fullcalendar

我正在使用fullcalendar和google calendar api,我将我的活动输出,并希望将它们作为json传递给我的fullcalendar,因为fullcalendar事件接受它作为数据源并自动将它们呈现到日历中。

我有我的html文件,其中包含许多资源和一个创建日历的jQuery脚本:

<html>
    <head>
        <link rel='stylesheet' href='fullcalendar/fullcalendar.css' />
        <script src='fullcalendar/lib/jquery.min.js'></script>
        <script src='fullcalendar/lib/moment.min.js'></script>
        <script src='fullcalendar/fullcalendar.js'></script>
        <script type='text/javascript' src='fullcalendar/gcal.js'></script>
        <script src='fullcalendar/lang/da.js'></script>

        <script type='text/javascript'>
            $(document).ready(function() {
                $('#calendar').fullCalendar({
                    defaultView: 'agendaWeek',
                    weekends: false,
                    lang: 'da',
                    header: false,
                    allDaySlot: false,
                    allDayText: '',
                    height: 695,
                    minTime: '06:00:00',
                    maxTime: '20:00:00',
                    events: 'calendarData.js'
                });
            });
        </script>
    </head>
    <body>
        <div id="calendar"></div>
    </body>
</html>

注意事件:将json对象放入。我有一个json文件,其中包含与我正在尝试创建的相同的硬编码json对象,并且工作正常。但是在以下javascript文件中出现了错误/错误。

calendarData.js

var CLIENT_ID = 'id';

var SCOPES = ["https://www.googleapis.com/auth/calendar.readonly"];

/**
 * Check if current user has authorized this application.
 */
function checkAuth() {
    gapi.auth.authorize(
        {
            'client_id': CLIENT_ID,
            'scope': SCOPES.join(' '),
            'immediate': true
        }, handleAuthResult);
}

/**
 * Handle response from authorization server.
 *
 * @param {Object} authResult Authorization result.
 */
function handleAuthResult(authResult) {
    var authorizeDiv = document.getElementById('authorize-div');
    if (authResult && !authResult.error) {
        // Hide auth UI, then load client library.
        authorizeDiv.style.display = 'none';
        loadCalendarApi();
    } else {
        // Show auth UI, allowing the user to initiate authorization by
        // clicking authorize button.
        authorizeDiv.style.display = 'inline';
    }
}

/**
 * Initiate auth flow in response to user clicking authorize button.
 *
 * @param {Event} event Button click event.
 */
function handleAuthClick(event) {
    gapi.auth.authorize(
        {client_id: CLIENT_ID, scope: SCOPES, immediate: false},
        handleAuthResult);
    return false;
}

/**
 * Load Google Calendar client library. List upcoming events
 * once client library is loaded.
 */
function loadCalendarApi() {
    gapi.client.load('calendar', 'v3', listUpcomingEvents);
}

/**
 * Print the summary and start datetime/date of the next ten events in
 * the authorized user's calendar. If no events are found an
 * appropriate message is printed.
 */
function listUpcomingEvents() {
    var request = gapi.client.calendar.events.list({
        'calendarId': 'primary',
        'timeMin': (new Date()).toISOString(),
        'showDeleted': false,
        'singleEvents': true,
        'maxResults': 10,
        'orderBy': 'startTime'
    });
    var json = {};

    request.execute(function(resp) {
        var events = resp.items;
        json.json = [];

        if (events.length > 0) {
            for (i = 0; i < events.length; i++) {
                var event = events[i];
                var when = event.start.dateTime;
                if (!when) {
                    when = event.start.date;
                }
                json.json.push({id : i+1, title : event.summary, start : event.start.dateTime, end : event.end.dateTime, desc : event.description});
            }
        }
    });
    return json;
}

正如您可能会看到,除了最后的json之外,这非常接近api日历javascript快速入门。我希望脚本将json对象返回到fullcalendar,但这不起作用,所以如果可能的话我怎么能改变它呢?

当我对对象进行字符串化并提醒时,我可以看到创建的对象与之前提到的json文件相同。

编辑: 我正在谈论的json文件以及可以使用的数据如下所示:

[{"id":"1","title":"Test 1","start":"2016-05-26","end":"2016-05-26T16:30:00","allDay":false},{"id":"2","title":"Test 2","start":"2016-05-26","end":"2016-05-26T17:00:00","allDay":false},{"id":"3","title":"Test 3","start":"2016-05-27T08:00:00","end":"","allDay":false}]

当我对字符串进行字符串化并提醒它时,它看起来像这样:

var myObject = JSON.stringify(json);
            alert(myObject);
{"json":[{"id":1,"title":"ghhgfgh","start":"2016-05-26T14:30:00+02:00","end":"2016-05-26T15:30:00+02:00"}]}

3 个答案:

答案 0 :(得分:1)

你的问题在这里:

$(document).ready(function () {
  $('#calendar').fullCalendar({
    defaultView: 'agendaWeek',
    weekends: false,
    lang: 'da',
    header: false,
    allDaySlot: false,
    allDayText: '',
    height: 695,
    minTime: '06:00:00',
    maxTime: '20:00:00',
    events: 'calendarData.js'
  });
});

&#34;事件&#34;不能将javascript文件作为输入或直接json字符串。您可以为其指定array of eventsURLfunction

我猜你打算提供&#34;事件&#34;使用 listUpcomingEvents()函数的结果。

你可以这样做(只需确保你在HTML文件中添加 calendarData.js 作为脚本src):

$(document).ready(function () {
  $('#calendar').fullCalendar({
    defaultView: 'agendaWeek',
    weekends: false,
    lang: 'da',
    header: false,
    allDaySlot: false,
    allDayText: '',
    height: 695,
    minTime: '06:00:00',
    maxTime: '20:00:00',
    events: function(start, end, timezone, callback){
              callback(listUpcomingEvents());
            },
  });
});

答案 1 :(得分:0)

要在您要使用的JS / JSON对象之间进行交互:

JSON.stringify()
JSON.parse()

参考是herehere

例如:JS&gt; JSON&gt; JS

var x = {
y: 'hello',
z: 1
};

console.log(JSON.parse(JSON.stringify(x)));

答案 2 :(得分:0)

将其转换为JSON对象,如下所示:

var Jobj = JSON.parse(your_string_data);