[英]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
功能作為響應。
// 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.