jQuery完整日历$ .ajax调用问题(在页面打开时使用静态事件)

时间:2022-08-24 22:08:53

So I am using Yii and full calendar as a widget which is called in a view of CalendarController. Uppon call for a widget, the widget retrives existing events from the DB and puts them inside the full calendar to display. Now I have also made a simple filter for filtering out events by category they are in ( dropdown with a submit ), so I want to send request to a calendarController method called actionEvents() which then takes what is passed to it ( the category of events for which we want to retrieve events ), gets them back to the jQuery which then calls the calendar again passing it a json_encode(d) array of needed properties to correctly render events under the selected category in the dropdown. The problem I have is that it seems fullcalendar is doing my wanted call ( POST ) as well as one another GET call along with it for some reason so it does return properly formatted json to the jQuery from the method of controller, but just shows an empty calendar without events in it on return. This is how the console looks like after the returned data.

所以我使用Yii和完整日历作为在CalendarController视图中调用的小部件。 Uppon调用一个小部件,小部件从数据库中恢复现有事件并将它们放在要显示的完整日历中。现在我还创建了一个简单的过滤器,用于按类别过滤掉事件(使用提交下拉列表),因此我想将请求发送到名为actionEvents()的calendarController方法,然后获取传递给它的内容(类别我们想要检索事件的事件),让他们回到jQuery,然后再调用日历,传递一个json_encode(d)所需属性的数组,以便在下拉列表中正确呈现所选类别下的事件。我遇到的问题是,似乎fullcalendar正在执行我想要的调用(POST)以及另一个GET调用以及它因为某些原因所以它确实从控制器的方法返回正确格式化的json到jQuery,但只是显示一个返回时没有事件的空日历。这是返回数据后控制台的样子。

jQuery完整日历$ .ajax调用问题(在页面打开时使用静态事件)

This is the code that calls ajax call

这是调用ajax调用的代码

$(document).ready(function() {
            var date = new Date(),
                d = date.getDate(),
                m = date.getMonth(),
                y = date.getFullYear();

            $('form.eventFilter').submit(function() {
                var selectedOption = $('form.eventFilter select').val(),
                    eventContainer = $('.fc-event-container');

                var objectToSend = { "categories" : [selectedOption],"datefrom" : "september2013"/*month + "" + year*/ , "dateto" : "september2013"/*month + "" + year*/};

                $.ajax({
                        url: '<?php echo Yii::app()->createUrl('calendar/events'); ?>',
                        type: "POST",
                        async:false,
                        data: {data : JSON.stringify(objectToSend)},
                        success: function(data) {

                            $('#fc_calendar').html('');
                            $('#fc_calendar').fullCalendar({
                                events: data
                            });
                            console.log(data);
                        },
                        error: function() {
                            console.log(data);
                        }

                    });

                return false;
            })
        })

The code that renders initial calendar events on first page load ( open ) is this

在第一页加载(打开)时呈现初始日历事件的代码就是这样

<div id="fc_calendar"></div>
    <script class="fc_calendar_script">
        // gets calendar and its events working and shown
        var date = new Date();
        var d = date.getDate();
        var m = date.getMonth();
        var y = date.getFullYear();

        $('#fc_calendar').fullCalendar({
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,basicWeek,basicDay'
            },
            editable: true,
            events: [
            <?php foreach ($eventItems as $event): ?>
            {
                title: '<?php echo htmlentities($event['eventItems']['title']); ?>',
                start: new Date(y,m,d + <?php echo $event['eventItems']['startdate_day_difference']; ?>),
                end:   new Date(y,m,d + <?php echo $event['eventItems']['enddate_day_difference']; ?>),
                url: '<?php echo $event['eventItems']['url']; ?>',
                className: [
                <?php foreach($event['eventCategories'] as $category) { echo ''.json_encode($category['slug']).','; }?> // and categories slugs as classnames, same purpose
                ]
            },
            <?php endforeach; ?>
            ]
        });
    </script>

The code in controller is not that important since you can see what it returns in the screenshot :) If someone has an idea of how to get around this I would really be grateful :) Tried everything I know

控制器中的代码并不重要,因为你可以在屏幕截图中看到它返回的内容:)如果有人知道如何解决这个问题我真的很感激:)尝试了我所知道的一切

Ok so bounty goes to whoever answers this question :) I am having problems with full calendar month rendering when ajax data is returned and events populated. Since I have checkboxes for each category ( events have MANY_MANY relation with categories ) and each time a checkbox is checked or unchecked, JSON array of chosen categories of events is passed on to PHP method which queries DB for all events that go under chose categories and returns all events in a jquery encoded array to the view which then takes that events array and rerenders the calendar like shown in the upper code. Problem is that when a checkbox is checked or unchecked and ajax returned the calendar always renders on the current month ( so right now it would always rerender itself to show events for september, untill the end of the month, then always for Ocbober and so on ), but what if a user was on lets say November 2013 when he checked event category for which he wanted to filter the events? The calendar would rerender on September still. How could I make it rerender on the month the user was on when he checked / unchecked a checkbox ?

好的,所以无论谁回答这个问题,我都会遇到问题。当返回ajax数据并填充事件时,我遇到完整日历月渲染问题。由于我有每个类别的复选框(事件与类别有MANY_MANY关系),并且每次选中或取消选中复选框时,所选事件类别的JSON数组将传递给PHP方法,该方法查询DB以查找所选类别下的所有事件。将jquery编码数组中的所有事件返回到视图,该视图然后获取该事件数组并重新呈现日历,如上面的代码所示。问题是当选中或取消选中复选框并且返回ajax时,日历总是在当前月份呈现(所以现在它总是会重新呈现自己以显示9月的事件,直到月末,然后总是为Ocbober等等) ),但是,如果用户打开了,那么可以说2013年11月他检查了他想要过滤事件的事件类别?日历仍将在9月份重新发布。如果我选中/取消选中复选框,我怎么能在用户登录的那个月重新渲染?

The code that I have which keeps track ( or at least it should ) of the current month when prev or next month buttons are clicked is this

我点击上一个或下个月按钮时跟踪(或至少应该)当前月份的代码是这个

$('.fc-button-next span').click(function(){
                start = $('#fc_calendar').fullCalendar('getView').visEnd;
                console.log(start);
            });

            $('.fc-button-prev span').click(function(){
                start = $('#fc_calendar').fullCalendar('getView').visStart;
                console.log(start);
            });

However this code is not tracking properly, sometimes it skips a month, sometimes it stays on the month without change and sometimes it returns propper month, which is bugging me so I cant call this function of the calendar properly which should set calendar to propper month on rerender.

然而,这段代码没有正确跟踪,有时它会跳过一个月,有时它会在月份没有变化,有时它会返回propper月,这会让我烦恼所以我不能正确地调用日历的这个功能,这应该将日历设置为propper month在rerender。

$('#fc_calendar').fullCalendar('gotoDate', start);

4 个解决方案

#1


3  

I think what you might be looking for is something like

我认为你可能正在寻找的是类似的东西

jQuery(function($){
    $('form.eventFilter').submit(function() {
        $('#fc_calendar').fullCalendar( 'refetchEvents' );
        return false;
    });

    $('#fc_calendar').fullCalendar({
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month,basicWeek,basicDay'
        },
        editable: true,
        events: function(start, end, callback) {

            var selectedOption = $('form.eventFilter select').val(),
                eventContainer = $('.fc-event-container');

            //create the data to be sent
            var objectToSend = {
                "categories": [selectedOption],
                "datefrom": start.getDate() + '-' + start.getMonth() + '-' + start.getYear(),
                "dateto": end.getDate() + '-' + end.getMonth() + '-' + end.getYear()
            };          

            //use jsonp based jQuery request
            $.ajax({
                url: 'events.json',
                data: objectToSend,
                cache: false
            }).done(function(data){
                //on success call `callback` with the data
                callback(data)
            })
        }
    });
});

Demo: Plunker

演示:Plunker

Note: The date param formatting and jsonp is not used here, you will have to change it to match your requirements

注意:此处不使用日期参数格式和jsonp,您必须更改它以符合您的要求

#2


1  

I see that you use JSON.stringify(data); this is what i tought your error was

我看到你使用JSON.stringify(data);这就是我所犯的错误

maybe you need a jsonp, and below you have my example

也许你需要一个jsonp,下面你有我的例子

$.ajax({
            'url': 'http://domain.com/index.php/api/news?callback=?',
            'data': {'data': JSON.stringify(data), callback: 'jsonPCallback'},
            'success': function(data) {
//                console.log(data);
            },
            jsonpCallback: jsonPCallback,
            dataType: 'jsonp'
        });

function jsonPCallback(cbdata){
        console.log('callback2')
//        console.log(cbdata);
        return false;
    }

now, do you also use something like

现在,你也使用类似的东西

echo $_GET['callback'].'('.CJSON::encode(array('status_live' => 1, 'data' => $data_decoded)).')';

in the controller to return the results ?

在控制器中返回结果?

also, createUrl might be wrong, because you need a absolute path

另外,createUrl可能是错误的,因为你需要一个绝对路径

#3


1  

Actualy the problem solution is as weird as the problem itself and it is the following. You must use designated way of doing an ajax call to fetch json that is in the plugin documentation, any other way you send your own call ( GET or POST ) and the calendar after that makes yet another call ( hence the another GET call ) if you are using just a "regular" $.ajax, $.post or $.get call using jQueries native functionality This should really be posted somewhere on the website in some section so that people do not get confused why their calendar is not making ajax calls and I wonder how noone else had similar problem before . So this is the "correct" documentation way of calling it with full calendar which you can find HERE

Actualy问题解决方案与问题本身一样奇怪,并且如下所示。您必须使用指定的方式执行ajax调用来获取插件文档中的json,以及您发送自己的调用(GET或POST)的任何其他方式,以及之后进行另一次调用的日历(因此另一个GET调用)你正在使用jQueries本机功能只使用“常规”$ .ajax,$ .post或$ .get调用这应该真的发布在某个部分的网站上,以便人们不会混淆为什么他们的日历没有制作ajax打电话,我想知道以前没有其他人有类似的问题。因此,这是使用完整日历调用它的“正确”文档方式,您可以在这里找到

$('#fc_calendar').html('');
                $('#fc_calendar').fullCalendar({

                    eventSources: [

                        // your event source
                        {
                            url: '?r=calendar/events',
                            type: 'POST',
                            data: { data : JSON.stringify(objectToSend)},
                            error: function(data) {
                                alert(data);
                            },
                        }

                        // any other sources...

                    ]

                });

So it will automaticly fetch any returned ( properly formatted data ) and use it to rerender new calendar with those events. It is very weird way of doing it, but the only way that will work.

因此,它将自动获取任何返回的(格式正确的数据)并使用它来重新呈现这些事件的新日历。这是非常奇怪的方式,但这是唯一可行的方法。

#4


0  

I can't comment so, you have an assignment to variable:"nothing" in your last query parameter

我无法评论,你有一个变量的赋值:你的上一个查询参数中的“nothing”

double check if you have looked for ajax request in your controller(important!),

如果您在控制器中查找了ajax请求,请仔细检查(重要!),

and also if this is this a 404 by the apache, you have url rewriting problems, and it looks like index.php is missing from url?!

如果这是apache的404,你有url重写问题,看起来url中缺少index.php ?!

#1


3  

I think what you might be looking for is something like

我认为你可能正在寻找的是类似的东西

jQuery(function($){
    $('form.eventFilter').submit(function() {
        $('#fc_calendar').fullCalendar( 'refetchEvents' );
        return false;
    });

    $('#fc_calendar').fullCalendar({
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month,basicWeek,basicDay'
        },
        editable: true,
        events: function(start, end, callback) {

            var selectedOption = $('form.eventFilter select').val(),
                eventContainer = $('.fc-event-container');

            //create the data to be sent
            var objectToSend = {
                "categories": [selectedOption],
                "datefrom": start.getDate() + '-' + start.getMonth() + '-' + start.getYear(),
                "dateto": end.getDate() + '-' + end.getMonth() + '-' + end.getYear()
            };          

            //use jsonp based jQuery request
            $.ajax({
                url: 'events.json',
                data: objectToSend,
                cache: false
            }).done(function(data){
                //on success call `callback` with the data
                callback(data)
            })
        }
    });
});

Demo: Plunker

演示:Plunker

Note: The date param formatting and jsonp is not used here, you will have to change it to match your requirements

注意:此处不使用日期参数格式和jsonp,您必须更改它以符合您的要求

#2


1  

I see that you use JSON.stringify(data); this is what i tought your error was

我看到你使用JSON.stringify(data);这就是我所犯的错误

maybe you need a jsonp, and below you have my example

也许你需要一个jsonp,下面你有我的例子

$.ajax({
            'url': 'http://domain.com/index.php/api/news?callback=?',
            'data': {'data': JSON.stringify(data), callback: 'jsonPCallback'},
            'success': function(data) {
//                console.log(data);
            },
            jsonpCallback: jsonPCallback,
            dataType: 'jsonp'
        });

function jsonPCallback(cbdata){
        console.log('callback2')
//        console.log(cbdata);
        return false;
    }

now, do you also use something like

现在,你也使用类似的东西

echo $_GET['callback'].'('.CJSON::encode(array('status_live' => 1, 'data' => $data_decoded)).')';

in the controller to return the results ?

在控制器中返回结果?

also, createUrl might be wrong, because you need a absolute path

另外,createUrl可能是错误的,因为你需要一个绝对路径

#3


1  

Actualy the problem solution is as weird as the problem itself and it is the following. You must use designated way of doing an ajax call to fetch json that is in the plugin documentation, any other way you send your own call ( GET or POST ) and the calendar after that makes yet another call ( hence the another GET call ) if you are using just a "regular" $.ajax, $.post or $.get call using jQueries native functionality This should really be posted somewhere on the website in some section so that people do not get confused why their calendar is not making ajax calls and I wonder how noone else had similar problem before . So this is the "correct" documentation way of calling it with full calendar which you can find HERE

Actualy问题解决方案与问题本身一样奇怪,并且如下所示。您必须使用指定的方式执行ajax调用来获取插件文档中的json,以及您发送自己的调用(GET或POST)的任何其他方式,以及之后进行另一次调用的日历(因此另一个GET调用)你正在使用jQueries本机功能只使用“常规”$ .ajax,$ .post或$ .get调用这应该真的发布在某个部分的网站上,以便人们不会混淆为什么他们的日历没有制作ajax打电话,我想知道以前没有其他人有类似的问题。因此,这是使用完整日历调用它的“正确”文档方式,您可以在这里找到

$('#fc_calendar').html('');
                $('#fc_calendar').fullCalendar({

                    eventSources: [

                        // your event source
                        {
                            url: '?r=calendar/events',
                            type: 'POST',
                            data: { data : JSON.stringify(objectToSend)},
                            error: function(data) {
                                alert(data);
                            },
                        }

                        // any other sources...

                    ]

                });

So it will automaticly fetch any returned ( properly formatted data ) and use it to rerender new calendar with those events. It is very weird way of doing it, but the only way that will work.

因此,它将自动获取任何返回的(格式正确的数据)并使用它来重新呈现这些事件的新日历。这是非常奇怪的方式,但这是唯一可行的方法。

#4


0  

I can't comment so, you have an assignment to variable:"nothing" in your last query parameter

我无法评论,你有一个变量的赋值:你的上一个查询参数中的“nothing”

double check if you have looked for ajax request in your controller(important!),

如果您在控制器中查找了ajax请求,请仔细检查(重要!),

and also if this is this a 404 by the apache, you have url rewriting problems, and it looks like index.php is missing from url?!

如果这是apache的404,你有url重写问题,看起来url中缺少index.php ?!