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

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

1
2
3
4
# devise respond_to json
config.to_prepare do
DeviseController.respond_to :html, :json
end

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

1
2
<%= 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头

1
2
3
4
5
6
7
8
9
$.ajaxSetup({
beforeSend: function(xhr){
var token;
token = $('meta[name="csrf-token"]').attr('content');
if (token) {
xhr.setRequestHeader('X-CSRF-Token', token);
}
}
});

4.js处理代码

1
2
3
4
5
6
7
8
9
10
11
12
$('#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获取错误集合。