如何在Rails中将动态路由传递给AJAX POST请求

Bre*_*ett 5 javascript ajax jquery ruby-on-rails fullcalendar

在我的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'
    });
});
Run Code Online (Sandbox Code Playgroud)

上面的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
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮我修复AJAX调用吗?我之前没有真正使用它,所以任何帮助将不胜感激!如果我要发布任何其他信息/代码,请告诉我.

Dev*_*wen 0

我可以看到您的代码中存在一些错误。

改变这个:

url: "{<%= profile_bookings_url(@profile) %>}"
Run Code Online (Sandbox Code Playgroud)

这样:

url: "<%= profile_bookings_url(@profile) %>"
Run Code Online (Sandbox Code Playgroud)