[英]pass two instance variables to js.erb files?
我需要将两个实例变量传递给ajax请求用来更新用户显示的javascript文件。 这就是我需要做的事情:
respond_to do |format|
if @post.save
format.js { @post @user_vote } # <-- right here
else
format.html { redirect_to :back, :alert => 'There was an error in removing the vote' }
end
end
这是怎么做到的?
如果使用js.erb文件,则无需传递实例变量。 您可以直接放置rails标记并在js.erb文件中访问这些变量
例如:
在您的控制器刚刚放
format.js #instead of format.js { @post @user_vote }
在js.erb文件中,您可以访问实例变量
$('#ele').html("<%= @post.name %>");
您的ActionController操作中的实例变量可在您的视图中自动获得。 比如你的控制器:
# posts_controller.rb
def update
# Your implementation here
@post = ...
@user_vote = ...
respond_to do |format|
if @post.save
format.js
format.html { redirect_to post_path(@post) }
else
format.js { ... }
format.html { redirect_to :back, ... }
end
end
end
然后在你的update.js.erb中:
# update.js.erb
console.log('Post: <%= @post.inspect %>');
console.log('User vote: <%= @user_vote %>');
# Your JS implementation here
(另外我注意到你在respond_to块中的逻辑可能会导致问题。你应该为@post.save
成功和失败条件渲染js和html格式。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.