在我的Rails应用程序中,我正在使用FullCalendar Rails gem并尝试使用jQuery / AJAX创建用户“预订”。我目前正在我的个人资料显示页面上的脚本标记中处理fullcalendar javascript,因为我不知道如何访问erb文件之外的动态路由。不幸的是,我的AJAX似乎根本不起作用。 select函数仍然可以正常运行,但AJAX似乎没有发生任何事情,因为我没有收到成功或失败消息,并且我的网络选项卡中没有显示任何内容。我猜我没有正确设置url路由,我也认为我对AJAX的一般设置可能不正确。更新:当我提交一个显示在fullcalendar javascript文件中的事件时,我实际上收到了一个控制台错误:'未捕获的TypeError:无法读取未定义'的属性'_calendar'。我不确定它的来源是什么,并且我的网络选项卡中仍然没有显示任何来自ajax请求。
<script>
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultDate: '2016-01-12',
selectable: true,
selectHelper: true,
select: function(start, end) {
var title = "Unavailable";
var eventData;
eventData = {
title: title,
start: start,
end: end,
color: 'grey'
};
$('#calendar').fullCalendar('renderEvent', eventData, true); // stick? = true
$('#calendar').fullCalendar('unselect');
$.ajax({
method: "POST",
data: {start_time: start, end_time: end, first_name: title, color: 'grey'},
url: "<%= profile_bookings_url(@profile) %>",
success: function(data){
console.log(data);
},
error: function(data){
alert("something went wrong, refersh and try again")
}
})
},
editable: true,
eventLimit: true, // allow "more" link when too many events
events: window.location.href + '.json'
});
});
上面的select函数使用jQuery向日历添加一个事件。我希望在我的AJAX中发生的事情是将该事件提交给我的预订在我的预订控制器中创建动作。
def create
@profile = Profile.friendly.find(params[:profile_id])
@booking = @profile.bookings.new(booking_params)
if @booking.save
flash[:notice] = "Sending your booking request now."
@booking.notify_host
redirect_to profile_booking_path(@profile, @booking)
else
flash[:alert] = "See Errors Below"
render "/profiles/show"
end
end
任何人都可以帮我修复AJAX通话吗?我之前没有真正使用它,所以任何帮助将不胜感激!如果我要发布任何其他信息/代码,请告诉我。
答案 0 :(得分:1)
我最终解决了这个问题。它与我的数据格式有关:我的ajax调用的元素。工作代码:
<script>
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultDate: '2016-01-12',
selectable: true,
selectHelper: true,
select: function(start, end) {
var title = "Unavailable";
var eventData;
eventData = {
title: title,
start: start,
end: end,
color: 'grey'
};
$.ajax({
method: "POST",
data: {booking:{start_time: start._d, end_time: end._d, first_name: title}},
url: "<%= profile_bookings_path(@profile, @booking) %>",
success: function(data){
console.log(data);
$('#calendar').fullCalendar('renderEvent', eventData, true); // stick? = true
$('#calendar').fullCalendar('unselect');
},
error: function(data){
alert("something went wrong, refersh and try again")
}
});
},
editable: true,
eventLimit: true, // allow "more" link when too many events
events: window.location.href + '.json'
});
});
它必须用预订对象包装,我的开始和结束时间是moment.js对象,所以我必须从那里访问实际的开始和结束时间。如果需要的话,我仍然对改进代码的领域感兴趣,但至少它正在发挥作用。
答案 1 :(得分:0)
我可以在您的代码中看到一些错误。
改变这个:
url: "{<%= profile_bookings_url(@profile) %>}"
由此:
url: "<%= profile_bookings_url(@profile) %>"