我使用了jQuery插件形式与我的Rails应用程序。我有一个这样的形式:
I am using the jQuery Form Plugin with my Rails app. I have a form like this:
<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文件中写有:
My application.js file has:
jQuery.ajaxSetup({
'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
});
$(document).ready(function(){
$("#comment_form").ajaxForm();
});
我的意见控制器是这样的:
My Comments controller is like this:
def create
@comment = Comment.new(params[:comment])
respond_to do |wants|
if @comment.save
flash[:notice] = 'Added comment.'
wants.js
end
end
end
和我有一些jQuery code在/views/comments/create.js.erb这样的:
And I have some jquery code in /views/comments/create.js.erb like:
$("#comment_form).hide();
和一些其他的东西。
我的问题是内部create.js.erb从未发生过jQuery的code(即形式没有得到隐藏)。如果我用这个在application.js中,而不是(感谢Railscast此code)
My problem is the jQuery code inside create.js.erb never happens (i.e. the form doesn't get hidden). If I use this in application.js instead (thanks to Railscast for this code)
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();
});
这一切工作正常。所有code在create.js.erb的伟大工程!我宁愿使用jQuery的表格插件,但我不明白如何让create.js.erb code运行。如果做这样的事情:
it all works fine. All the code in create.js.erb works great! I'd rather use the jQuery Form plugin, but I don't understand how to make create.js.erb code run. If do something like:
$("#comment_form").ajaxForm({success: function(){$("comment_form").hide()}});
那么jQuery的code工作。但我需要运行ERB模板(因为我做的事情一样呈现一个局部内)。
then that jQuery code works. But I need to run the erb template (because I do things like render a partial inside).
感谢您的任何见解。
我想通了这一点。在观看此截屏 HTTP://blog.edgecase .COM / 2009/6/15 / Ajax的文件上传制作 - 易截屏 - 我注意到他补充说数据类型:脚本 而不是这样,
I figured this out. While watching this screencast http://blog.edgecase.com/2009/6/15/ajax-file-uploads-made-easy-screencast - I noticed he added dataType: 'script' So, instead of
$("#comment_form").ajaxForm();
我需要
$("#comment_form").ajaxForm({dataType: 'script'});
作品!而且它是正确的,在jQuery的表格文档 - 如果dataType =='脚本'服务器响应在全球范围内被评为
Works! And it's right there in the jQuery Form docs - "if dataType == 'script' the server response is evaluated in the global context"