Ruby on rails 是否将两个实例变量传递给js.erb文件?
我需要将两个实例变量传递给一个javascript文件,ajax请求使用该文件来更新用户显示。这就是我需要做的:Ruby on rails 是否将两个实例变量传递给js.erb文件?,ruby-on-rails,ruby-on-rails-3,Ruby On Rails,Ruby On Rails 3,我需要将两个实例变量传递给一个javascript文件,ajax请求使用该文件来更新用户显示。这就是我需要做的: 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 remov
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
respond|to do |格式|
如果@post.save
format.js{@post@user_vote}#'删除投票时出错'}
结束
结束
这是如何实现的?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
#update.js.erb
console.log('Post:');
log('User vote:');
#您的JS实现在这里
(我还注意到您在respond_to块中的逻辑可能会导致问题。您应该针对
@post.save
的成功和失败条件呈现js和html格式)如果使用js.erb文件,则无需传递实例变量。您可以直接将rails标记放入js.erb文件中并访问这些变量
例如:
在你的控制器里,把
format.js #instead of format.js { @post @user_vote }
在js.erb文件中,您可以访问实例变量
$('#ele').html("<%= @post.name %>");
$('#ele').html(“”);