当前位置: 动力学知识库 > 问答 > 编程问答 >

ajax - Rails Render JSON - Session Lost?

问题描述:

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

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!

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.

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

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:

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.

网友答案:

I put that in beforeSend method:

function goAjax(urlAddress,dataObject,successFunction,errorFunction){
        $.ajax({
              type: "POST",
              url: urlAddress,
              beforeSend: function ( xhr ) {
                    xhr.setRequestHeader("X-CSRF-Token", $('meta[name=csrf-token]').attr('content'));
              },
              dataType: "json",
              contentType: "application/json; charset=utf-8",
              processData: false,
              data: JSON.stringify(dataObject),
              context: document.body,
              success: function(data,status){ successFunction(data,status);},
              error: function(data,status){ errorFunction()}
        });
    }

works great if you don't need to use other way of ajax request(in this way you should add beforeSend to all ajax requests)

分享给朋友:
您可能感兴趣的文章:
随机阅读: