【发布时间】:2009-06-12 17:39:27
【问题描述】:
我在 Rails 应用程序中使用 jQuery 表单插件。我有这样的表格:
<form action="/comments" id="comment_form" method="post">
<textarea cols="60" id="comment_comment" name="comment[comment]" rows="3"></textarea>
<input id="comment_submit" name="commit" type="submit" value="Add comment" />
</form>
我的 application.js 文件有:
jQuery.ajaxSetup({
'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
});
$(document).ready(function(){
$("#comment_form").ajaxForm();
});
我的评论控制器是这样的:
def create
@comment = Comment.new(params[:comment])
respond_to do |wants|
if @comment.save
flash[:notice] = 'Added comment.'
wants.js
end
end
end
我在 /views/cmets/create.js.erb 中有一些 jquery 代码,例如:
$("#comment_form).hide();
还有一些其他的东西。
我的问题是 create.js.erb 中的 jQuery 代码永远不会发生(即表单没有被隐藏)。如果我在 application.js 中使用它(感谢 Railscast 提供此代码)
jQuery.fn.submitWithAjax = function() {
this.submit(function() {
$.post(this.action, $(this).serialize(), null, "script");
return false;
})
return this;
};
jQuery.ajaxSetup({
'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
});
$(document).ready(function(){
$("#comment_form").submitWithAjax();
});
一切正常。 create.js.erb 中的所有代码都运行良好!我宁愿使用 jQuery Form 插件,但我不明白如何让 create.js.erb 代码运行。如果做类似的事情:
$("#comment_form").ajaxForm({success: function(){$("comment_form").hide()}});
那么 jQuery 代码就可以工作了。但我需要运行 erb 模板(因为我会在内部渲染部分内容)。
感谢您提供任何见解。
【问题讨论】:
标签: jquery ruby-on-rails ajax forms