[英]Rails error messages in login form with AJAX
我認為我遇到了復雜的問題,但讓我們保持簡單。 我正在使用devise,我想在登錄頁面的表單下方顯示錯誤消息。 現在,當用戶在控制台中輸入錯誤密碼時,出現了錯誤POST 401 (Unauthorized)
但頁面中未顯示錯誤。
slice_code.js.erb
$(document).ready(function() {
var form = $('.centralized-login')
form.submit( function(event) {
event.preventDefault()
var email = $('#email-input').val()
var password = $('#password-input').val()
var req = $.ajax('/user_role', {
data: {
email
}
})
req.then( function(result) {
var { role } = result
switch (role) {
case 'company_manager':
$.ajax('/users/sign_in', {
method: "POST",
data: {
"user[email]": email ,
"user[password]": password,
"authenticity_token": $('input[name="authenticity_token"]').val()
},
success: function(data, textStatus, req){
window.location="/users/sign_in"
}
})
break;
我應該添加類似$("ajax:error")
嗎?
_new.html.erb
<div class="col-sm-8 col-md-6 col-xs-12">
<div class="vr-textfield-wrapper">
<%= f.email_field :email, id: "email-input", class: "vr-textfield", placeholder: t('users.passwords.new.email_placeholder'), required: true, aria_required: true, autofocus: true %>
<span class="vr-field__invalid-msg"><%= t 'users.passwords.new.valid_email'%></span>
<% if resource.errors.full_messages_for(:email).first %>
<div class="vr-textfield-wrapper">
<div class="alert alert-danger">
<div class="error-explanation">
<%= t('activerecord.errors.models.user.attributes.email.not_found_in_database') %>
</div>
</div>
</div>
<% end %>
</div>
</div>
編輯
success: function(data, textStatus, req){
window.location="/users/sign_in"
},
error: function (jqXHR, textStatus, errorThrown) {
$('.centralized-login').find('.error-explanation').html(errorThrown)
console.log(textStatus + " " + errorThrown);
}
})
sessions_controller.rb
class Users::SessionsController < Devise::SessionsController
include LogoutUsergroups
def after_sign_out_path_for(_user)
new_user_session_path
end
end
您可以在視圖文件本身的js響應(create.js.erb)中呈現錯誤。 像下面這樣
<%- if resource.errors.any? %>
var id = $('form#Id') <!-- Replace with your selector -->
<% resource.errors.each do |key, value| %>
id.find('selector').html("<%= "#{key.to_s.humanize} #{value}" %>");
<% end %>
<%- end %>
或者您可以像使用成功函數一樣使用錯誤函數,
$.ajax({
success: function(data, textStatus, req){
window.location="/users/sign_in"
}
error: function (jqXHR, textStatus, errorThrown) {
id.find('selector').html(""); # Use the error here to show in the UI.
console.log(textStatus + " " + errorThrown);
}
});
使用remote: true
時應使用$("ajax:error")
remote: true
對於表單提交,則為remote: true
。 供參考: https : //github.com/rails/jquery-ujs/wiki/ajax
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.