我正在尝试在rails上设置一个表单,以便在提交之后,一个新的部分,一个新的表单将异步地呈现在旧表单的位置上。
当我们的API被使用时,我们的控制器从我们的API模型中调用类方法,根据环境向我们的开发URI或生产URI发送params。
现在的情况是这样的:
注册表格在这里:
= 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对象。有什么方法可以异步显示我的错误消息或fadeOut()我的旧表单和fadeIn()我的新表单吗?
谢谢!几个小时来一直在琢磨这个问题:
发布于 2015-11-19 06:50:48
在有表单的ERB文件中,您需要添加一个AJAX侦听器。然后,您可以启动一些jQuery/Javascript,让它在成功和错误时做一些事情。
您需要给表单一个ID,以便侦听器知道听什么:
= form_for "user", url: register_path, remote: true, id: 'id-of-form' ...
再培训局文件:
<% 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
endhttps://stackoverflow.com/questions/33795834
复制相似问题