使用ajax响应使用数据填充表单

时间:2017-04-30 19:07:28

标签: jquery ruby-on-rails ajax

我目前在使用ajax响应将值传递到编辑表单时遇到问题,如果我只是通过html响应并渲染表单,它会获取传入的电子邮件值。但是我没有运气试图做这是通过ajax。我有什么明显的错误吗?

edit.js.erb

$('#edit-admin-modal').modal('show');
$('#admin_email').val('<%= @admin.email %>');
console.log('<%= @admin.email %>');

index.html.haml

  - @admins.each do |admin|
        %tr#admin[admin]
          %td= admin.email
          %td= admin.last_sign_in_at
          %td= admin.last_sign_in_ip
          %td.buttonColumn
            %button.adminShow.adminButton.btn.btn-primary{ type: 'button', disabled: 'disabled' } Show
          %td.buttonColumn
            = link_to 'Edit', "admins/#{admin.id}/edit", remote: true, class: 'btn btn-warning adminButton admin-edit'
          %td.buttonColumn
            = link_to 'Delete', "admins/#{admin.id}", method: :delete, remote: true, data: { confirm: 'Are you sure?' }, class: 'btn btn-danger adminButton'

_edit_form.html.haml

= form_for @admin, :url => {:action => "update", :id => @admin.id} do |f|
  .form-inputs.modal-body
    .form-group.row
      = f.label :email, 'Email',  class:('col-sm-2 col-form-label'), required: true
      .col-sm-10
        = f.email_field :email, class:('form-control')
        %div#emailUnique.confirmMessage
    .form-group.row
      = f.label :password, 'Password', class:('col-sm-2 col-form-label'), required: true
      .col-sm-10
        = f.password_field :password, class:('form-control')
    .form-group.row
      = f.label :confirm_Password, 'Confirm Password', class:('col-sm-2 col-form-label')
      .col-sm-10
        = f.password_field :password_confirmation, class:('form-control'), required: true
        %div#confirmMessage.confirmMessage
  .modal-footer
    = f.submit 'Update Admin', class:('btn btn-primary'), id:('admin-submit')

_edit_account_modal.html.haml

.modal#edit-admin-modal.fade{:role => "dialog", :tabindex => "-1"}
  .modal-dialog{:role => "document"}
    .modal-content
      .modal-header
        %button.close{"aria-label" => "Close", "data-dismiss" => "modal", :type => "button"}
          %span{"aria-hidden" => "true"} ×
        %h4.modal-title Update Account
        = render 'edit_form'

admins_controller.rb

def edit
    @admin = Admin.find(params[:id])
    respond_to do |format|
      format.html{redirect_to admins_url}
      format.js
    end
  end

1 个答案:

答案 0 :(得分:2)

我不会单独编辑每个字段。相反,也许可以在JS响应中使用ERB重新发送表单。

$('#edit-admin-modal').modal('show');
$('.modal-content .some-form-wrapper').html('<%= j render "edit_form" %>')

这将表现为 rails中的HTML响应。

确保将文件重命名为.js.erb