我正在弹出模态框来提交表单。如果存在验证问题,表单应该刷新,但仍在模态框内。这适用于添加新记录,我相信这是调用:create操作,POST。我想使用相同的模式框来编辑记录。到目前为止,我可以在模式框中打开它,但只要出现错误,它就会重定向到另一个页面,而不是留在框中。我认为ajax并没有调用这个动作来返回javascript来将表单放回模态框中。如何获得ajax将JavaScript返回到模式框以更正表单?Rails如何通过Ajax调用返回javascript:更新控制器动作
例子,这里是我的:创建行动:
def create
@user = User.new(params[:user])
respond_to do |format|
if @user.save
format.js { render :redirect } #this is for modalform
format.html { redirect_to(users_url, :notice => 'User was successfully created.') }
else
format.html {render :new}
format.js # this renders the create.js.erb file to keep the form inside
end
end
end
下面是加载模式对话框,并保持内部,直到验证是否正确形式的javascript:
document.observe('dom:loaded', function() {
$('newuser-link').observe('click', function(event) {
event.stop();
Modalbox.show(this.href,
{title: 'Create',
width: 500, #up to this point, this opens the form in the modal box
afterLoad: function() { # this afterload part is supposed to keep the form inside the modal box
$('new_user').observe('submit', function(event) {
event.stop();
this.request();
})
}}
);
});
})
这里是.js.erb文件:创建操作时调用如果存在验证错误以将窗体保留在模式框内:
$('MB_content').update("<%= escape_javascript(render :partial => 'form') %>");
Modalbox.resizeToContent();
$('new_users').observe('submit', function(event) {
event.stop();
this.request();
});
因为这适用于:create动作,所以当我想编辑记录时,如何使它适用于:update动作?再次,主要问题是,如果存在验证错误,它将重定向到模态框之外。
UPDATE:
我发现,是应该保持模式对话框打开的JavaScript的一部分:
$('new_user').observe('submit', function(event) {
event.stop();
this.request();
的“new_user”是形式的ID。当使用此编辑记录时,表单的编号为edit_user_1或edit_user_32或正在编辑的任何用户。所以我想这里的解决方案,我不明白,是如何使用JavaScript中的类作为选择器而不是id。因为当我手动输入'edit_user_1'并且我正在编辑id为1的用户时,它可以工作......但显然不适用于任何其他用户。