我的 application.js 中有一个 AJAX 调用,它将 3 条数据发送到我的 events_controller#check 操作:
//application.js
$(document).on('click', "#check-button", function(){
...
$.ajax({
url: '/events/check',
data: {checkList: checkList , selected_date: selectedDate , length: length },
}
);
});
我的检查操作:
#events_controller.rb
def check
checkList = params[:checkList]
selected_date = params[:selected_date]
length = params[:length]
busy_array = Array.new #this needs to be rendered in the view
...
busy_array.push(user.id) #busy_array is a list of user ids from database
end
#routes.rb
resources :events do
get :check, on: :collection
end
View :
<button id="check-button" type="button">Check</button>
<div class = "col-md-6" id="unavailable">
<h2>Unavailable on this day:</h2>
<ol id="unavailable-list">
<li>THIS LIST SHOULD BE POPULATED BY BUSY_ARRAY</li>
</ol>
</div>
现在我需要将数据从 events_controller#check
发送回 View ,但我不知道如何发送 busy_array
以在 events 中呈现\new.html.erb
感谢您的帮助,我是 ruby/JS 初学者
最佳答案
busy_array = Array.new #this needs to be rendered in the view
如果必须在 View 中可用,则需要定义一个 @instance
变量:
def check
checkList = params[:checkList]
selected_date = params[:selected_date]
length = params[:length]
@busy_array = Array.new
...
@busy_array.push(user.id) #busy_array is a list of user ids from database
end
每次调用 controller#action
时,action
内的数据/变量都会受到 local scope 的约束。 .
在 View
中输出数据需要变量在类的整个实例中可用(不仅仅是操作/函数)。因此@busy_array
。
修复
#app/views/events/....
<%= button_to "Check", events_check_path %>
<div class = "col-md-6" id="unavailable">
<h2>Unavailable on this day:</h2>
<ol id="unavailable-list"> </ol>
</div>
#app/assets/javascripts/application.js
$(document).on('click', "#check-button", function(e){
...
$.get('/events/check', {checkList: checkList , selected_date: selectedDate , length: length});
});
#app/controllers/events_controller.rb
class EventsController < ApplicationController
def check
@busy_array = User.joins(:event).where(event: { ... }).pluck(:id) #-> return user ids where event.x = y
respond_to do |format|
format.js #-> invokes app/views/events/check.js.erb
format.html #-> invoked when HTML request sent
end
end
end
#app/views/events/check.js.erb
<% @busy_array.each do |id| %>
$("ol#unavailable-list").append("<%=j id %>")
<% end %>
<小时/>
I don't know how to send
busy_array
to be rendered inevents\new.html.erb
如果该变量是 @instance
var,则该变量将在 new
中可用:
#app/views/events/new.html.erb
<%= @busy_array %>
view
是 EventsController
类实例的一部分,但在 check
方法的范围之外。当您向 Rails 发送请求时,它会使用 Controller
的实例来编译一组 HTML 以返回到您的浏览器。
例如,您可以将 EventsController
流程总结如下:
Request > Routing > EventsController.new(request).action > Returned HTML
如果您手动设置 EventsController.new(request)
,您将得到以下结果:
@event = EventsController.new request
@event.check #-> "busy_array" locally scoped to this function
@event.response #-> outputs view code.... @busy_array needs to be instance var
如果您阅读MVC
,您会更好地理解:
关于javascript - 如何使用 AJAX 将数据从 ruby Controller 发送到应用程序 javascript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35310746/