我有以下代码:
comment.js.erb
alert("Alert");application.js
jQuery.ajaxSetup({
'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})
jQuery.fn.submitWithAjax = function() {
this.submit(function() {
$.post(this.action, $(this).serialize(), null, "script");
return false;
})
return this;
};
$(document).ready(function() {
$(".comment_form").submitWithAjax();
})查看表单:
<% form_for :comment, :url => comment_task_path(tasks.id),
:html => {:remote => true,
:class => "comment_form"} do |f|-%>
<%= f.text_field :remark, :placeholder => "Add Comments", :rows => 2,
:class => 'box',
:style => "width: 834px; height: 40px;"%>
<%= f.submit "Comment"%>
<% end -%>控制器方法:
def comment
@comment = Comment.new(params[:comment])
@comment.user_id = @current_user.id
@task.comments << @comment
flash[:notice] = "thank you"
if @comment.save
# what code do I put here to render comment.js.erb?
else
end
end如果我希望comment方法呈现我的comment.js.erb,我需要放入什么代码?我尝试了render to和respond to,但它仍然不能运行。
发布于 2013-03-20 12:15:13
不需要显式呈现comment.js.erb。默认情况下,控制器将在执行该方法后呈现comment.js.erb。也许你可以使用下面的代码。
in comment操作
def comment
# ...
@comment.save
end在comment.js.erb文件中
<% if @comment.valid? %>
alert("Comment created successfully");
<% else %>
alert("Something went wrong.");
<% end %>发布于 2013-03-20 12:07:11
你需要在插件中传递FORM作为参数。
jQuery.fn.submitWithAjax = function(elem, options, arg) {发布于 2013-03-20 13:48:12
在路由中添加获取comments.js.erb的get请求
获取'your_controller_name/comments',:as => 'comments‘
在您的控制器中,只需使用comments_path
https://stackoverflow.com/questions/15515073
复制相似问题