ruby-on-rails之Rails Devise Ajax 调用

findumars 阅读:12 2024-10-01 17:34:08 评论:0

我需要通过 ajax 调用处理登录设计。现在我有一个用简单表单构建的设计登录,设计的存在完全适用于服务器端。客户端是完全独立于 ruby​​ 构建的。客户端人员需要知道如何使用正确的参数通过 AJAX 发送信息以处理登录和登录。

编辑

我的 application.js 看起来像这样

// This is a manifest file that'll be compiled into including all the files listed below. 
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically 
// be included in the compiled file accessible from http://example.com/assets/application.js 
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the 
// the compiled file. 
// 
//= require jquery 
//= require jquery_ujs 
//= require_tree . 
$(function(){ 
  $.ajaxSetup({ 
    beforeSend: function( xhr ) { 
      var token = $('meta[name="csrf-token"]').attr('content'); 
      if (token) xhr.setRequestHeader('X-CSRF-Token', token); 
    } 
  }); 
}); 

这是我的发帖请求

function signIn(email, password){ 
 
    var data = {user: {email: email, password: password}}; 
    $.ajax({ 
        url: 'http://localhost:3000/users/sign_in.json', 
        type: 'POST', 
        dataType: 'json', 
        data: data, 
        success: function(data, textStatus, xhr) { 
            alert('success'); 
            alert(data); //to see what kind of outputs these have 
            alert(textStatus); 
            alert(xhr); 
 
        //called when successful 
        } 
    }); 
} 

这在我的 Rails 控制台中给出了这个

Started POST "/users/sign_in.json" for 127.0.0.1 at 2011-12-08 12:30:06 -0500 
Processing by SessionsController#create as JSON 
Parameters: {"user"=>{"email"=>"someone@hotmail.com", "password"=>"[FILTERED]"}} 
WARNING: Can't verify CSRF token authenticity 
User Load (0.1ms)  SELECT "users".* FROM "users" WHERE "users"."email" = 'someone@hotmail.com' LIMIT 1 
(0.3ms)  UPDATE "users" SET "last_sign_in_at" = '2011-12-08 17:29:23.030686', "current_sign_in_at" = '2011-12-08 17:30:07.069479', "sign_in_count" = 11, "updated_at" = '2011-12-08 17:30:07.069864' WHERE "users"."id" = 16 
Completed 201 Created in 144ms (Views: 2.1ms | ActiveRecord: 0.0ms) 

在我的浏览器中,当我检查元素并转到我得到的控制台时

XMLHttpRequest cannot load http://localhost:3000/users/sign_in.json. Origin null is not allowed by Access-Control-Allow-Origin. 

而且我的所有提醒都没有显示。

我需要改变什么

请您参考如下方法:

默认情况下,您应该编写如下代码:

首先在您的 application.js 中设置 CSRF token :

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

其次发布您的登录信息:

$.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 
  } 
}); 


标签:ajax
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号