加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

devise ajax请求

发布时间:2020-12-16 00:27:36 所属栏目:百科 来源:网络整理
导读:devise默认已经有较好的ajax支持了,只需要简单的配置一下即可使用ajax登录/注册。 1. 修改config/application.rb加下以下配置,启用json输出。 # devise respond_to json config.to_prepare do DeviseController .respond_to :html , :json end 2. 修改form

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,115)">:as => resource_name,115)">:url => session_path(resource_name),115)">:remote => true,115)">html: {id: 'ajax_user_signin',115)">data: {type: :json}}) do |f| %>
$.ajaxSetup({
  beforeSend: function(xhr){
    var token;
    token = $('meta[name="csrf-token"]').attr('content');
    if (token) {
      xhr.setRequestHeader('X-CSRF-Token',token);
    }
  }
});
'#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获取错误集合

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读