我正在彈出模態框來提交表單。如果存在驗證問題,表單應該刷新,但仍在模態框內。這適用於添加新記錄,我相信這是調用: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的用戶時,它可以工作......但顯然不適用於任何其他用戶。