繁体   English   中英

Rails设计Ajax调用

[英]Rails Devise Ajax call

我需要通过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令牌:

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

暂无
暂无

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

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