开发者

Cookie Access over JSONP

I have a page in domain.com that makes a JSONP ajax request (using jQuery's .getJSON() function) to a URL in anotherdomain.com. I thought (read: assumed) that the resource in anotherdomain.com would have server-side access to any cookies set in that domain, but that doesn't seem to be the case?

The ajax call is being done specifically to access a particular cookie, do some data manipulation and return a rich set of information keyed by the cookie value. The original domain doesn't have direct access to the cookie value, so I thought that an ajax request would maintain the state I need.

Which pivotal piece of information about cookies am I overlooking? I'm exhausted and I'm just not seeing it.

Thanks.

UPDATE

I found a way of doing it, but it looks like JSONP to my eye, so I'm wondering why this way works while the Ajax version doesn't. Is the request just disconnected from the browser session so that no cookies are accessible?

<script type="application/x-javascr开发者_如何学Goipt" src="<?php echo $service_url . '&callback=interests' ?>"></script>
<script type="text/javascript">
  function interests( data ) {
    $( function() {
      var c_behaviors = data.length;
      var ids         = [];

      for( var i = 0; i < c_behaviors; i++ ) {
        ids.push( data[i].behavior_id );
      }

      $('body').append( '<p><label>Returned:</label> ' + ids.join( ', ' ) + '</p>' );       
    });
  }
</script>


The same origin policy applies to all ajax requests, so if the domain being accessed in an ajax call is different than the domain loaded in the browser (document.host), all cookies associated with the domain in the requested url will not be sent up. Therefore, the JSONP approach works because it writes out a new script tag in the window, which will behave like any resource request a browser could make to an external domain (hence passing all the cookies associated with the domain in the url). I have also confirmed this by simply calling $.post("http://atdmt.com") from my chrome console, while on stackoverflow.com in the browser (the only other domain that had cookies in my browser, while writing up the answer) and it did not send up any cookies in the request headers.

Another solution to get around the problem of maintaining state for anotherdomain.com would be to have anotherdomain.com set a first party cookie (by not setting the domain attribute of the cookie) and when an ajax/json request is made to anotherdomain.com access those cookies via javascript and push them up the request using standard HTTP params.

Hope I have helped.


I have encountered the same problem before. The issue I found is that most browsers won't let you ESTABLISH a session (i.e. set a session cookie) when the same origin policy isn't being met.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜