繁体   English   中英

如何使用AJAX呈现html.erb部分

[英]How to render an html.erb partial using AJAX

我是编程新手,我不知道该如何做:

我在events\\new.html.erb视图中选择了一个集合,一个客户可以在其中选择另一个客户:

#events\new.html.erb
<%= f.collection_select :id,
                                    Customer.where(business_id: current_customer.business_id),
                                    :id,
                                    :full_name,
                                    { prompt: 'Select' },
                                    { id: "colleageselect", onChange: "renderColCal(this)" } %>


            <div id = colleaguecal>

            </div>

当用户单击一个名称时,它将触发一个客户端JavaScript函数,该函数创建一个变量colleagueID ,我需要在Ruby服务器端使用该变量,以便从数据库中检索选定的客户

#application.js

function renderColCal(select){

    var colleagueID = select.value ;


    document.getElementById("colleaguecal").innerHTML = "Your colleague's calendar:";

    $.ajax({
            url: 'calendars_controller/calendarChange',
            data: (
                'colleagueID=' + $('select').val()
            )
        }
    )
}

该变量在Calendars#calendarChange中获取:

def calendarChange
    colleagueID = params[:colleagueID]
    @colleague = Customer.where(id: :colleagueID)

    @colcalendar = @colleague.calendar
    @events = @colleague.calendar.events #sets the variables I need to use for the customer's calendar (_calendarChange.html.erb) that needs to be rendered within events\html.erb

  end

calendars\\_calendarChange ,以便在更改collection_select选择时,使用calendars#calendarChange中定义的@events变量在我的events\\html.erb呈现calendars\\_calendarChange

谢谢!

编辑:

明确说明我要完成的工作:

我希望客户能够在collection_select中选择另一个客户,并在同一页面上看到所选客户的日历。 该日历要求@events ,以便对所选客户唯一。 (每个客户都有自己的日历和事件集)

如果我了解您要完成的工作:

ruby / rails世界中,作为惯例,我们对方法和变量使用蛇格命名法。 因此,此处calendarChange将变为calendar_change

调用函数renderColCal时,它将命中calender_change方法。

您需要在此处创建一个calendars/calendar_change.js.erb ,该calendars/calendar_change.js.erb将提供javascript功能作为响应。

日历/calendar_change.js.erb

// put here whatever javascript you want
// You could also use ruby code by wrapping it with erb tags
// Here an example:
$("#wrapper").html("<%= escape_javascript(render @events ) %>")

更多信息在这里

暂无
暂无

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

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