-1

无法在 Javascript 中为 Cakephp 获取正确格式的数据数组。我正在使用 Fullcalendar 制作日程安排日历,并将事件加载到数组中。

外部事件是用户从另一个 div 拖到日历上,并传输他们的姓名和用户 ID。接下来,日历被初始化,当用户被放到它上面时,用户会显示在日历上并添加到arrayOfEvents中。这是我们正在使用的变量。

$(document).ready(function() { 
    /* initialize the external events -----------------------------------------------------------------*/
    $('#external-events div.external-event').each(function() {
        // create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
        // it doesn't need to have a start or end
        var eventObject = {
            title: $.trim($(this).text()), // use the element's text as the event title
            userId: this.id
        };
        // store the Event Object in the DOM element so we can get to it later
        $(this).data('eventObject', eventObject);
        // make the event draggable using jQuery UI
        $(this).draggable({
            zIndex: 999,
            revert: true, // will cause the event to go back to its
            revertDuration: 0  //  original position after the drag
        });
    });
    /* initialize the calendar-----------------------------------------------------------------*/   
    $('#calendar').fullCalendar({
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'agendaWeek,agendaDay'
        },
        defaultView: 'agendaWeek',
        editable: true,
        events: [
            <?php foreach ($users as $user) { foreach ($user['Event'] as $event): ?>
            {
                start: '<?php echo $event['start_date']; ?>',
                end: '<?php echo $event['end_date']; ?>',
                title: '<?php echo $event['title']; ?>',
                allDay: false,
                color: '#077169'
            },
            <?php endforeach; } ?>
        ],
        droppable: true, // this allows things to be dropped onto the calendar !!!
        drop: function(date, allDay) { // this function is called when something is dropped
            // retrieve the dropped element's stored Event Object
            var originalEventObject = $(this).data('eventObject');
            // we need to copy it, so that multiple events don't have a reference to the same object
            var copiedEventObject = $.extend({}, originalEventObject);
            // assign it the date that was reported
            copiedEventObject.start = date;
            copiedEventObject.end = (date.getTime() + 3600000) / 1000; // default shift length is 1 hour
            copiedEventObject.userId = originalEventObject.userId;
            copiedEventObject.allDay = false;
            // render the event on the calendar
            // the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
            $('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
            // Push events into array
            arrayOfEvents.push(copiedEventObject); 
            console.log(arrayOfEvents);
        }
    });
});  // End document ready
var arrayOfEvents = [];
var data = {};

function updateSchedule() { // Function clicked on in link to send arrayOfEvents to controller to add to database
    // You can get all events out of the array here
    for (var i = 0; i < arrayOfEvents.length; i++) {
        var event = arrayOfEvents[i];
        data += "Event" + i
                + "&user_id=" + event.userId
                + "&start_date=" + event.start
                + "&end_date=" + event.end
                + "&title=" + event.title;
    }
    // Make your ajax post here
    $.ajax({
        type: "POST",
        url: "<?php echo $this->webroot; ?>events/add",
        data: data,
        success: function(response) {
            alert('done!');
        },
        fail: function(response) {
            alert("error");
        }
    });
}

updateSchedule函数与 onClick 事件相关联并提交到视图,但格式不正确我需要数组看起来像这样:

Array
(
    [Event] => Array
    (
        [0] => Array
        (
            [user_id] => 'value'
            [start_date] => 'value'
            [end_date] => 'value'
            [title] => 'value'
        ),
        [1] => Array
        (
            [user_id] => 'value'
            [start_date] => 'value'
            [end_date] => 'value'
            [title] => 'value'
        )
   )
)

目前它看起来像:

array(
    'Event' => 'Event0',
    'user_id' => '4',
    'start_date' => 'Tue Apr 30 2013 11:30:00 GMT-0400 (Eastern Daylight Time)',
    'end_date' => 'Tue Apr 30 2013 12:30:00 GMT-0400 (Eastern Daylight Time)',
    'title' => 'value'
)

我对如何将其更改为我想要的格式有点迷茫。

4

1 回答 1

1

看起来您需要用对象和数组的组合来表示 Javascript 中的结构,然后将其输出到 JSON。您的data变量应构造为如下对象:

var data = {};
for (var i = 0; i < arrayOfEvents.length; i++) {
    var event = arrayOfEvents[i],
        eventId = "Event" + i,
        eventData = {};
    if (!data[eventId]) data[eventId] = [];

    eventData['user_id'] = event.userId;
    eventData['start_date'] = event.start;
    eventData['end_date'] = event.end;
    eventData['title'] = event.title;

    data[eventId].push(eventData);
}

然后$.ajax调用可以处理将其转换为 json 如果您设置dataType: "json"

$.ajax({
    type: "POST",
    url: "<?php echo $this->webroot; ?>events/add",
    data: data,
    dataType: "json",
    success: function(response) {
        alert('done!');
    },
    fail: function(response) {
        alert("error");
    }
 });

然后控制器必须解码 JSON 字符串并将其转换为所需的 PHP 数组。请参阅此问题以了解如何设置:如何处理作为 HTTP Post 发送到 cakephp 应用程序的 json 数据?

于 2013-04-29T17:06:32.250 回答