[英]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.