devise使用ajax登录

左手 posted @ 2013年12月18日 18:29 in 积累点滴 with tags devise配置json devise配置ajax devise ajax 登录 devise ajax signin , 2239 阅读

devise默认已经有较好的ajax支持了,只需要简单的配置一下即可使用ajax登录/注册。

1. 修改config/application.rb加下以下配置,启用json输出。

# devise respond_to json
config.to_prepare do
  DeviseController.respond_to :html, :json
end

2. 修改form标签,添加data-remote, data-type,设置id

<%= form_for(resource, :as => resource_name, :url => session_path(resource_name), :remote => true,
 html: {id: 'ajax_user_signin', data: {type: :json}}) do |f| %>

3. 设置ajax头

$.ajaxSetup({
  beforeSend: function(xhr){
    var token;
    token = $('meta[name="csrf-token"]').attr('content');
    if (token) {
      xhr.setRequestHeader('X-CSRF-Token', token);
    }
  }
});

4. js处理代码

$('#ajax_user_signin').on('ajax:complete', function(e, xhr, type){
  if (type === 'success') {
    location.href = '/';
  } else {
    try {
      alert(xhr.responseJSON.error);
      // this.reset();
    } catch (e$) {
      e = e$;
    }
  }
});

关于注册:
注册的方法和登录基本相同,给form_for添加data-remote、data-type和id等属性。需要注意的是注册返回的表单验证是多项错误,使用xhr.resonseJSON.errors获取错误集合。

Avatar_small
UP Board Question Pa 说:
2022年8月29日 18:32

UP Board 10th Previous Question Paper 2023 are very important for the Preparation of Public Exam of UPMSP for the Students. 10th Students of can easily get their Latest and most valuable Mock Test Paper from this website. UP Board Question Paper Students only have to Download the UP Board 10th Mock Test Paper 2023 for all the important subjects are available Including the English, Hindi, Mathematics, Science, Social Science etc. UP Board 10th Model Paper 2023, UP 10th High School Question Paper 2023 Blueprint, UP Board 10th English, Hindi, Mathematics, Science, Social Science Exam Important Question Paper 2023 Download.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter