问题
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.
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");
});
My link where ajax call is called is via this line of code
'showcomment' , :id =>article, :remote => true ,:class=>'show_comment' %>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
How can this be done?
回答1:
I just wanted to try and expand on the other answers a little bit.
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 });
This is a typical jquery ajax call
$.ajax({
url: "test.html",
type: "POST"
}).done(function() {
$( this ).addClass( "done" );
});
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
});
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
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.
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.
回答2:
change showcomment to this:
def showcomment
@article = Article.find(params[:article_id])
@comment = @article.comments.find(params[:id])
respond_to { |format| format.js }
end
In showcomments.js.erb you can access both objects @article and @comment.
A sample use is as below:
$('#yourdiv').html('');
回答3:
You render nothing when responding to js format. So code in showcomments.js.erb isn't evaluated. Remove { render :nothing => true } in controller and do whatever you want in showcomments.js.erb. BTW you don't need ajax:success event. It is the end of request already.
showcomments.js.erb
$('.show_comment').closest('tr').html("");
来源:https://stackoverflow.com/questions/24824557/ajax-success-callback-in-ruby-on-rails