gpt4 book ai didi

ruby-on-rails-3 - Rails 3 设计 Ajax 登录捕获错误消息

转载 作者:行者123 更新时间:2023-12-04 20:18:19 25 4
gpt4 key购买 nike

我在:
导轨 3.0.9
设计 1.4.7
jquery-ujs

我做了什么?...
1) 我已经使用 data-remote="true"设置了登录表单。
2) 我已经设置了登录 jquery 处理程序:

('form#user-reg-form')
.bind("ajax:beforeSend", function(evt, xhr, settings){
})
.bind("ajax:success", function(evt, data, status, xhr){
$('#comments').append(xhr.responseText);

})
.bind('ajax:complete', function(evt, xhr, status){
})
.bind("ajax:error", function(evt, xhr, status, error){
try {
errors = $.parseJSON(xhr.responseText);
} catch(err) {
errors = {message: "Please reload the page and try again"};
}
errorText = "There were errors with the submission: \n<ul>";

for ( error in errors ) {
errorText += "<li>" + error + ': ' + errors[error] + "</li> ";
}

errorText += "</ul>";

// Insert error list into form
$form.find('div.validation-error').html(errorText);
});

3)我像这样重新定义了 session Controller :
  def create
resource = warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#failure")
sign_in(resource_name, resource)
return render :json => { :success => true, :content => current_user.email }
end

def failure
return render:json => {:success => false, :errors => ["Login failed."]}
end

4)我已经设置了我的 route.rb 文件:
devise_for :users, :controllers => {:sessions => "sessions"}

一切正常……但是当我传递错误的电子邮件或密码时,我收到了来自用户模型(可能来自 Devise)的未捕获消息“电子邮件或密码错误”。但我想捕捉这条消息并将其放入 json 对象中,就像这样 return render:json => {:success => false, :errors =>////邮箱或密码错误////}

问题是: :recall 不起作用。看起来像那个 Warden.authenticate!没有看到我的失败方法

最佳答案

解决方案非常简单)
我必须在中设置config/initializers/devise.rb :

config.http_authenticatable_on_xhr = false
config.navigational_formats = [:html, :json]

关于ruby-on-rails-3 - Rails 3 设计 Ajax 登录捕获错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9641273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com