简体   繁体   English

结合使用fullcalendar.io和JSONP

[英]Using fullcalendar.io with JSONP

I'm trying to add public holidays to full calendar. 我正在尝试将公共假期添加到完整日历中。 http://fullcalendar.io/ http://fullcalendar.io/

var actionUrl =  @Html.Raw(Json.Encode(@Url.Action("Calendar", "Lecture")));

        $('#fullcalendar').fullCalendar({
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,agendaWeek,agendaDay'
            },
            eventTextColor : "Black",
            eventSources: [

            {
                url: actionUrl,
                data: function() {
                    return {
                        campusIds: getCampusIds(),
                        lectureRoomIds: getLectureRoomsIds(),
                        lecturerIds: getLecturerIds(),
                        eventTypeIds: getEventTypeIds(),
                    }
                },
                error: function() {
                    alert('there was an error while fetching events!');
                },
                traditional: true
            },

            {
                url: "http://kayaposoft.com/enrico/json/v1.0/?action=getPublicHolidaysForMonth&month=1&year=2013&country=zaf?callback=?",
                error: function() {
                    alert('there was an error while fetching events!');
                },
            }
        ],

The first event source works and that fetches json from my mvc controller. 第一个事件源有效,并且可以从我的mvc控制器获取json。 The second source however doesn't. 但是第二个来源没有。 I understand I need to use jsonp and I think I need to map the returning data over to something that full calendar understands but I can't get this right. 我知道我需要使用jsonp,我想我需要将返回的数据映射到整个日历都可以理解的东西,但是我做不到。 Please assist! 请协助!

Thanks 谢谢

To begin with you need to make a call with valid parameters to the url ie 首先,您需要使用有效参数调用url,即

http://kayaposoft.com/enrico/json/v1.0/?action=getPublicHolidaysForMonth&month=1&year=2013&country=eng

This would return data in the following format: 这将以以下格式返回数据:

[{"date":{"day":1,"month":1,"year":2015,"dayOfWeek":4},"localName":"New Year's Day","englishName":"New Year's Day"}]

It is then a case of translating that data into the format that expects ie EventData . 然后是将数据转换为期望的格式,即EventData的情况

This is done by iterating over the date objects returned via the json as follows but setting the properties you need (in the below demo I set the title and start): 这是通过如下迭代遍历通过json返回的日期对象来完成的,但是设置所需的属性(在下面的演示中,我设置标题并开始):

  var items = [];
  $.each( json, function( key, val ) {
      items.push({ title : val.localName, start : val.date } );
  });

This all needs to be wrapped up in a getJson call ie 所有这些都需要包装在getJson调用中,即

$.getJSON( "http://kayaposoft.com/enrico/json/v1.0/?action=getPublicHolidaysForMonth&month=3&year=2013&country=eng", function( data ) {

  $.each( data, function( key, val ) {
      items.push({ title : val.localName, start : val.date } );
  });  

});

You can the set your calendar items as follows (simplified for demo): 您可以按以下方式设置日历项目(为演示简化):

$('#calendar').fullCalendar({
    events: items
});

jsFiddle 的jsfiddle

 var items = []; var json = [{"date":{"day":1,"month":1,"year":2015,"dayOfWeek":4},"localName":"New Year's Day","englishName":"New Year's Day"}] $.each( json, function( key, val ) { items.push({ title : val.localName, start : val.date } ); }); $('#calendar').fullCalendar({ events: items }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.2.6/fullcalendar.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.2.6/fullcalendar.css" rel="stylesheet"/> <div id='calendar'></div> 

Revised answer 修改后的答案

I've found a solution. 我找到了解决方案。 The service you are using for your dates has the API documentation here . 您用于约会的服务在此处具有API文档。 The relevant portion: 相关部分:

JSONP JSONP

In each operation you can use JSONP like this: Sample URL returning public holidays in Austria for January 2013: JSON_URL?action=getPublicHolidaysForMonth&month=1&year=2013&country=aut&jsonp=myfunction 在每个操作中,您都可以像这样使用JSONP:2013年1月在奥地利返回公共假日的示例URL: JSON_URL?action=getPublicHolidaysForMonth&month=1&year=2013&country=aut&jsonp=myfunction

So change callback to jsonp and it should work. 因此,将callback更改为jsonp ,它应该可以工作。 Also, it works best with FC if you give a range instead of a month. 另外,如果您指定范围而不是一个月,则它与FC搭配使用效果最佳。 Your ajax call should look like: 您的ajax调用应如下所示:

events: function (start, end, timezone, callback) {
    console.log(start.format('YYYY-MMM'));
    $.ajax({
        type: "get",
        url: 'http://kayaposoft.com/enrico/json/v1.0/?action=getPublicHolidaysForDateRange&jsonp=?',
        data: {
            country: "zaf",
            fromDate: start.format('DD-MM-YYYY'),
            toDate: end.format('DD-MM-YYYY')
        },
        dataType: 'jsonp',
        contentType: 'application/json',
        success: function (data) {
            var events = [];
            $.each(data, function (i, holiday) {
                events.push({
                    start: moment({
                        year: holiday.date.year,
                        month: holiday.date.month - 1, //momentjs uses base 0 months
                        day: holiday.date.day
                    }),
                    title: holiday.englishName,
                    allDay: true
                });
            });
            callback(events);
        }
    }).fail(function (jqXHR) {
        alert("failed to get holidays");
    });

Here is a working JSFiddle . 这是一个正在工作的JSFiddle

Old answer: (still applicable for non-jsonp servers) 旧答案:(仍适用于非jsonp服务器)

If you are trying to do a cross domain json request (jsonp), the server needs to support it. 如果您尝试执行跨域json请求(jsonp),则服务器需要支持它。

JSONP requests are wrapped in script tags and must therefore be valid JS. JSONP请求包装在脚本标签中 ,因此必须是有效的JS。 A literal object is not valid JS (like {a:'b'} ). 文字对象不是有效的JS(例如{a:'b'} )。

jQuery handles this by sending a callback function name parameter to the server. jQuery通过向服务器发送回调函数名称参数来处理此问题。 It looks like: 看起来像:

callback=jQuery21003313164389692247_1423682275577

The server must wrap the response data in this function like: 服务器必须使用以下函数包装响应数据:

jQuery21003313164389692247_1423682275577( {id:"2",name:"me"} );

which is now valid and executable JS. 现在是有效且可执行的JS。

So, unless that server's API allows for JSONP requests, you cannot do cross domain requests to it. 因此,除非该服务器的API允许JSONP请求,否则您无法对其进行跨域请求。 This is a security limitation of web browsers. 这是Web浏览器的安全限制。

As an alternative, you could proxy the data through your server. 或者,您可以通过服务器代理数据。 Have fullcalendar make requests to your server which in turn loads data from the external source and sends it back to the client. 向您的服务器发出全日历请求,服务器再从外部源加载数据并将其发送回客户端。

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

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