繁体   English   中英

Ruby on Rails AJAX表单到外部API

[英]Ruby on Rails AJAX form to External API

我正在尝试在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对象,以及一个用户或一条错误消息。 有没有一种方法可以让我异步显示我的错误消息,或者异步显示我的旧窗体并淡出我的新窗体?

谢谢! 磨了几个小时:'(

在拥有表单的ERB文件中,您需要添加一个AJAX侦听器。 然后,您可以触发一些jQuery / Javascript,并使其在成功和错误上有所作为。

您将需要给您的表单一个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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM