簡體   English   中英

Rails如何通過Ajax調用返回javascript:更新控制器動作

[英]Rails how to return javascript via Ajax call in :update controller action

我正在制作一個彈出模式框來提交表單。 如果存在驗證問題,表單應該刷新,但仍然在模態框內。 這適用於添加新記錄,我相信它正在調用:create action,POST。 我想使用相同的模態框來編輯記錄。 到目前為止,我可以在模態框中打開它,但只要有錯誤,它就會重定向到另一個頁面,而不是留在框內。 我認為ajax沒有調用動作來返回javascript以將表單放回模態框中。 如何讓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文件:如果存在驗證錯誤以保持表單在模式框內,則:create動作調用:

$('MB_content').update("<%= escape_javascript(render :partial => 'form') %>");
Modalbox.resizeToContent();
$('new_users').observe('submit', function(event) {
event.stop();
this.request();
});

因為這適用於:創建操作,當我想編輯記錄時,如何使其適用於:update操作? 同樣,主要問題是當存在驗證錯誤時,它會重定向到模態框之外。

更新
我發現在javascript中應該保持模態框打開的部分:

$('new_user').observe('submit', function(event) {
                event.stop();
                this.request();  

'new_user'是表單的id。 使用此編輯記錄時,表單的ID為edit_user_1或edit_user_32或正在編輯的任何用戶。 所以我想這里的解決方案,我無法弄清楚,是如何在javascript中使用一個類作為選擇器而不是id。 因為當我手動輸入'edit_user_1'並且我正在編輯id為1的用戶時,它可以工作......但顯然不適用於任何其他用戶。

我沒有使用ModalBox,而是最終使用了FaceBox(這里的教程):

http://net.tutsplus.com/tutorials/ruby/how-to-build-an-unobtrusive-login-system-in-rails/

這幾乎是相同的,但在為選擇器添加類或id方面似乎更靈活。 另外,當涉及到動態,rails生成id時,我使用了一個小jQuery來創建一個變量來獲取動態鏈接並將其傳遞給選擇器:

var myid = jQuery('#userform').children().attr('id');

然后,它要求我傳入的表單的id

'#' + myid  

無論如何,我按照上面的教程開始工作,甚至可以修改它以添加新用戶和編輯它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM