【问题标题】:Ruby on Rails AJAX form to External APIRuby on Rails AJAX 表单到外部 API
【发布时间】:2016-02-21 02:52:41
【问题描述】:

我正在尝试在 Rails 上设置一个表单,以便在提交后,带有新表单的新部分将异步呈现在旧表单的位置。

当我们的 API 被使用时,我们的控制器从我们的 API 模型中调用类方法,根据环境将参数发送到我们的开发 URI 或生产 URI。

就目前而言,事情是这样的:

注册表在这里:

= form_for "user", url: register_path, remote: true, :authenticity_token => true, :remote => :true, :method => :post do |f|
    = f.text_field :email, required: true
    = f.password_field :password, required: true
    = f.button "Sign Up", :type => "submit"

控制器正在收集数据,将其发送到我们的注册用户方法,如下所示:

def register_new_user(referral_code = nil)
  response = self.class.post('/user/register',
    :body => {
      :email => @user[:email],
      :pass => @user[:password],
      :device_origin => "web"
    }.to_json
  )

  return response
end

响应将包含一个 JSON 对象,带有用户或错误消息。有没有办法让我异步显示我的错误消息或淡出()我的旧表单和淡入淡出()我的新表单?

谢谢!已经研究了好几个小时了:'(

【问题讨论】:

  • 我点击了向上箭头。它说它不会显示,直到我有 15 声望

标签: jquery ruby-on-rails ruby ajax forms


【解决方案1】:

在您拥有表单的 ERB 文件中,您需要添加一个 AJAX 侦听器。然后你可以触发一些 jQuery/Javascript 并让它在 Success 和 Error 上做一些事情。

您需要为表单提供一个 ID,以便听众知道要听什么:

= form_for "user", url: register_path, remote: true, id: 'id-of-form' ...

ERB 文件:

<% content_for :javascript do %>
  <script type="text/javascript">

    $(document).on('ajax:success', '#id-of-form', function(event, response) {
      var email = response.body.email
      $('#user-email').html(email)
      // Just an example, not sure what your response looks like
    });

    $(document).on('ajax:error', '#id-of-form', function(event, response) {
      $('#error').html(response.error).hide().fadeIn('slow')
    });
  </script>
<% end %>

您可能还希望在控制器中更具体地说明如何响应:

def register_new_user(referral_code = nil)
  response = self.class.post('/user/register',
      :body => {
        :email => @user[:email],
        :pass => @user[:password],
        :device_origin => "web"
      }.to_json
  )

  # I'm assuming this is in your controller and the method for register_path?

  if response.ok?
    render json: { body: response }, status: 200
  else
    render json: { error: 'Something went wrong' }, status: 400
  end
end

【讨论】:

    猜你喜欢
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多