导轨渲染JSON - 会议失去了什么? [英] Rails Render JSON - Session Lost?

查看:120
本文介绍了导轨渲染JSON - 会议失去了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一些Ajax调用到一个控制器,它响应JSON。

i am trying to make some Ajax calls to an controller which responds with JSON.

if session[:user]
  render :json => "Some Data"
else
  render :json => "You are not logged in"
end

第一次这个动作被调用由authed用户一切正常,并会议![:用户] =零。 第二次,它被称为是

The first time this action gets called by an authed user everything is ok and session[:user] is != nil. The second time it gets called it is nil!

因此​​,它似乎像Rails是失去它的会话,只要我做的渲染:JSON 。我想通了,第一个电话轨内将覆盖 * _会议 -cookie一个新的。作为该钢轨的后果不知道最初,authed,会话。

So it seems like rails is loosing it's session as soon as i do render :json. I figured out that within the first call rails overrides the *_session-cookie with a new one. As consequence of that rails doesn't know about the initial, authed, session.

如果我不渲染响应作为JSON一切工作正常。

If i don't render the response as JSON everything works fine.

如何强制导轨设置相同的SessionID以JSON呈现的页面作为正常的看法?

How to force rails to set the same sessionid in JSON rendered pages as in normal views?

推荐答案

经过六天的搜索我终于做到了的:

After six days of searching I finally made it:

好像铁轨破坏,因为缺少 X-CSRF令牌头了会议。我在JQuery中的 ajaxSend 挂钩,现在加入这个标题中:

Seems like rails destroys the session because of the missing X-CSRF-Token Header. I am adding this header now in in the ajaxSend Hook of JQuery:

$(document).ajaxSend(function(e, xhr, options) {
  var sid = $("meta[name='csrf-token']").attr("content");
  xhr.setRequestHeader("X-CSRF-Token", sid);
});

它按预期工作了。

It's working as expected now.

这篇关于导轨渲染JSON - 会议失去了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆