简体   繁体   English

使用Rails remote设计ajax登录/注册:true

[英]Devise ajax login/register with Rails remote: true

Without remote: true in my form, the login works. 如果没有remote: true在我的表单中为remote: true ,则登录有效。 But, when using remote: true , and attempting to login via ajax, I receive this error: 但是,当使用remote: true并尝试通过ajax登录时,我收到此错误:

You need to sign in or sign up before continuing.

The requests are both post. 这些请求都已发布。 Can somebody enlighten me? 有人可以启发我吗?

There are some steps that you need to follow: 您需要遵循一些步骤:

1) Check whether the request made is of javascript. 1)检查所发出的请求是否为javascript。

To verify that you should check the request header to see what the Accept parameter is. 要验证您应该检查请求标头以查看什么是Accept参数。 If it says application/javascript then it's all good. 如果它显示application/javascript那么一切都很好。 Use tools like firebug to check the request headers easily. 使用萤火虫等工具轻松检查请求标头。

2) What javascript files are included? 2)包含哪些javascript文件?

Secondly, a very common problem when starting to try out the :remote => true is that the required javascript libraries are not included in your code. 其次,当开始尝试:remote => true时,一个非常常见的问题是所需的javascript库未包含在您的代码中。 So my guess is that the following code is missing from your layout: 所以我的猜测是您的布局中缺少以下代码:

<%= javascript_include_tag :defaults %>
<%= csrf_meta_tag %>

If that is the case, just include it inside the html header. 如果是这种情况,只需将其包含在html标头中即可。

3) Check the controller: does it have a respond_to block? 3)检查控制器:它是否有response_to块?

If you generated your app with rails generate scaffold , it will have something like 如果您使用rails generate scaffold生成了应用程序,则该应用程序将具有以下内容

 respond_to do |format|
      format.html
      format.xml  { .... }
    end

Replace the above code with: 将上面的代码替换为:

respond_to :html, :js

OR 要么

respond_to do |format|
      format.html
      format.js
      format.xml  { .... }
    end

4) Setup CSRF Token in your application.js 4)在application.js中设置CSRF令牌

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

5) Post your login information 5)发布您的登录信息

$.ajax({
  url: '/users/sign_in.json',
  type: 'POST',
  dataType: 'json',
  data: {user: {email: 'email@example.com', password: 'password'}},
  success: function(data, textStatus, xhr) {
    //called when successful
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM