我正在使用jQuery表單插件與我的Rails應用程序。我有一個表格是這樣的:如何在Rails js.erb模板中使用jQuery Form插件?
<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
而且我有一些jQuery代碼/ views/comments/create.js.erb like:
$("#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模板(因爲我在做一些內部渲染)。
感謝您的任何見解。