Ruby on Rails中的Ajax成功回调 [英] Ajax success callback in ruby on rails
问题描述
我想在我的ruby on rails教程中实现ajax,控制器将在处理ajax请求时返回一个对象.我不知道要处理我的JavaScript文件中的响应. 我想根据javascript文件中返回的对象来更新一些div.
Hi want to implement ajax in my ruby on rails tutorials and the controller will return an object on handling the ajax request. I dont know to handle the response in my javascript file. I want to update some div based on object returned in javascript file.
这是我在showcomments.js.erb中写的内容
Here is what I have written in my showcomments.js.erb
$('.show_comment').bind('ajax:success', function() {
$(this).closest('tr')="Something here from the object returned");
});
我的调用ajax的链接是通过这一行代码
My link where ajax call is called is via this line of code
<td><%= link_to 'Show Comment', :action => 'showcomment' , :id =>article, :remote => true ,:class=>'show_comment' %></td>
我处理此请求的控制器动作如下
My controller action where this request is handled is like this
def showcomment
@article = Article.find(params[:article_id])
@comment = @article.comments.find(params[:id])
respond_to do |format|
format.js{ render :nothing => true }
end
end
这怎么办?
推荐答案
我只是想尝试扩展其他答案.
I just wanted to try and expand on the other answers a little bit.
在rails中,当您将:remote => true
添加到链接时,它实际上会处理jquery ajax调用的第一部分.这就是为什么您不需要bind.(ajax:success, function(){ #
do stuff here });
In rails when you add :remote => true
to a link it essentially takes care of the first part of a jquery ajax call. That's why you don't need bind.(ajax:success, function(){ #
do stuff here });
这是一个典型的jquery ajax调用
This is a typical jquery ajax call
$.ajax({
url: "test.html",
type: "POST"
}).done(function() {
$( this ).addClass( "done" );
});
Rails负责第一部分,直到.done
回调.因此,您的javascript erb模板中的所有内容都会像这样
Rails takes care of the first part, up to the .done
callback. So anything in your javascript erb template is put in the callback like this
.done(function() {
#your showcomments.js.erb file is inserted here
});
要从控制器呈现showcomments.js.erb模板,只需执行此操作
To render the showcomments.js.erb template from the controller just do this
def showcomment
@article = Article.find(params[:article_id])
@comment = @article.comments.find(params[:id])
respond_to do |format|
format.js
end
end
format.js之后不需要任何内容,因为此时默认的rails动作是呈现与动作名称相同的js模板,在本例中为showcomment.js.erb
.
You don't need anything after format.js because the default rails action at that point is to render a js template with the same name as the action, in this case it's showcomment.js.erb
.
现在,您知道单击该链接时,它将直接渲染该showcomment
模板,并且其中的所有JavaScript都将立即运行. Rails使使用ajax非常简单.希望对您有所帮助.
Now you know when that link is clicked it will go straight to rendering that showcomment
template , and any javascript in there will be run instantly. Rails makes using ajax very simple. I hope that helps.
这篇关于Ruby on Rails中的Ajax成功回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!