我知道这是一种基本的,但我有问题从控制器发送数据到。js。在我的rails应用程序中的动词页面
我可以使用remote=>true从我的link_to函数调用我的主控制器。这段代码在我的index.html.erb页面
<%= link_to 'Process', post, method: :delete, data: { confirm: 'Are you sure?' },:remote=>true,:class=>"test" %>
在我的控制器中,我做了一些事情,并希望返回一些数据到默认的ajax返回页,这将是index.js.erb
def destroy
@post = Post.find(params[:id])
@post.destroy
@test = 1
respond_to do |format|
format.html { redirect_to posts_url }
format.json {render json: @test}
format.js #this will redirect me to index.js.erb page where i would like to manipulate @test
end
end
这是微不足道的,但你能告诉我们如何设置pass @test到index.js.erb,以便我可以使用它作为数据,也检索它
谢谢
你可以像使用html模板一样在js模板中使用实例变量。唯一需要注意的是,您需要将服务器输出包装在javascript_escape
中。
# index.js.erb
$('#some-div').html('<%= j(@test) %>)
j
是javascript_escape
的别名