简体   繁体   English

从javascript返回json对象

[英]Returning json object from javascript

I'm working with fullcalendar, and the google calendar api where I get my events out and want to deliver them to my fullcalendar as json since the fullcalendar event accept that as a datasource and automatically renders them into the calendar.我正在使用 fullcalendar 和 google calendar api,我可以在其中获取我的事件并希望将它们作为 json 传送到我的 fullcalendar,因为 fullcalendar 事件接受它作为数据源并自动将它们呈现到日历中。

I have my html file which includes a number of ressources and a jQuery script that creates the calendar:我有我的 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>

Notice the events: that takes the json object in. I have a json file with identical hardcoded json object as the one i'm trying to create and that works fine.请注意事件:将 json 对象带入。我有一个 json 文件,其硬编码 json 对象与我正在尝试创建的对象相同,并且工作正常。 But something fails/is wrong in the following javascript file.但是在以下 javascript 文件中出现了问题/错误。

calendarData.js日历数据.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;
}

As you might see this is very close to the api calendar javascript quickstart apart from the json at the end.正如您可能看到的,除了最后的 json 之外,这与 api 日历 javascript 快速入门非常接近。 I would like the script to return a json object to the fullcalendar but this doesn't work, so how could I change this if possible?我希望脚本将 json 对象返回到 fullcalendar 但这不起作用,所以如果可能,我该如何更改呢?

When i stringify and alert the object I can see that the object created is the same as the previously mentioned json file that does work.当我字符串化并提醒对象时,我可以看到创建的对象与前面提到的有效的 json 文件相同。

Edit: The json file i'm talking about and which data can be used looks like this:编辑:我正在谈论的 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}]

When I stringify and alert the object it looks like this:当我字符串化并提醒对象时,它看起来像这样:

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"}]}

Your problem is here:你的问题在这里:

$(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'
  });
});

The "events" can't get a javascript file as an input nor as a direct json string. “事件”无法将 javascript 文件作为输入,也无法作为直接的 json 字符串。 You can give it an array of events , a URL or a function .你可以给它一个事件数组、一个URL或一个函数

I guess you intended to feed the "events" with the results of listUpcomingEvents() function.我猜你打算用listUpcomingEvents()函数的结果来提供“事件”。

You can do it that way (just make sure your you add the calendarData.js as script src in your HTML file as well):您可以这样做(只需确保您在 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());
            },
  });
});

To interract between JS / JSON object you've to use:要在 JS / JSON 对象之间进行交互,您必须使用:

JSON.stringify()
JSON.parse()

Reference are here and here参考在这里这里

For example: JS > JSON > JS例如:JS > JSON > JS

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

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

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

var Jobj = JSON.parse(your_string_data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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