【问题标题】:AJAX for rendering a partial or showing form errors用于呈现部分或显示表单错误的 AJAX
【发布时间】:2013-04-19 19:08:51
【问题描述】:

我在使用 Rails 以 AJAX 方式解决表单处理时遇到了困难。我将尝试解释我所拥有的不同部分,以及我确实有疑问的地方:

这是我的 new.html.erb 的样子:

<%= simple_form_for(resource, :as => resource_name, :url => registration_path(resource_name), :remote => true) do |f| %>
  <%= f.input :email, :label => false, :placeholder => 'Enter Email' %>
  <%= f.submit "Step inside", :id => 'invitation_button' %>
<% end %>

<div id="request_invite">
</div>

如您所见,我有一个:remote =&gt; true,所以提交是通过 AJAX 完成的。另外,我有一个空容器(#request_invite),它会装满一个部分,以防提交成功。

这是我的 registrations_controller.rb(创建方法) 的样子:

def create
    build_resource

    if resource.save
      if resource.active_for_authentication?
        sign_in(resource_name, resource)
        respond_with resource, :location => after_sign_up_path_for(resource)
      else
        expire_session_data_after_sign_in!
        respond_with resource, :location => after_inactive_sign_up_path_for(resource)
      end
    else
      clean_up_passwords resource
      respond_with resource
    end
  end

我的疑惑就在这里。我应该写什么才能让JS知道提交成功与否。如果成功,我想将一个名为_thank_you.html.erb 的部分渲染到#request_invite 容器中。如果不成功,我想在表单中显示错误。

这是我处理 AJAX 响应的 Javascript 文件:

$('document').ready(function() {
  $("#new_user").on('ajax:success', function(data, status, xhr)
  {
    alert("test");
  })
});

现在 alert("test") 总是出现,因为我没有办法知道是否成功。

非常感谢,我希望我能很好地解释自己。

【问题讨论】:

    标签: ruby-on-rails ajax forms devise partial


    【解决方案1】:

    如果您进行了手动 ajax 调用,并在提交表单时进行成功和失败回调(而不是使用 remote: true)。我累了,不确定我是否完全按照您的控制器操作尝试执行操作。

      $('#form_name').submit (e) ->
        e.preventDefault()
        $.ajax
          type: "POST"
          url: "/whatever_the_path_is"
          data: { 'email': $(@).val() }
          success: (result) ->
            $('#request_invite').html(result)
          failure: ->
            $('#request_invite').html("<h1>Request Failed</h1>")
    

    你的控制器可能看起来像:

    def create
          build_resource
    
          if resource.save
            if resource.active_for_authentication?
              sign_in(resource_name, resource)
              # respond_with resource, :location => after_sign_up_path_for(resource)
              render partial: '/partials_folder/thank_you'
            else
              expire_session_data_after_sign_in!
              # respond_with resource, :location => after_inactive_sign_up_path_for(resource)
              render partial: '/partials_folder/there_was_an_error'
            end
          else
            clean_up_passwords resource
            respond_with resource
          end
        end
    

    希望这能让你走上正确的道路。

    【讨论】:

      猜你喜欢
      • 2014-12-23
      • 2012-05-22
      • 2016-02-19
      • 1970-01-01
      • 2013-11-07
      • 2013-02-21
      • 2016-01-27
      • 1970-01-01
      • 2012-05-05
      相关资源
      最近更新 更多