可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
A javascript application running on 10.0.0.1
tries to authenticate it's users with cross-domain ajax calls.
The request looks like:
function test(again){ $.ajax({ type: 'GET', url: 'http://example.com/userinfo', dataType: 'json', success: function(userinfo){ if(again) test(false);}});} test(true);
The first response from the server tries to set a cookie:
Access-control-allow-origin:http://10.0.0.1 Set-Cookie:PHPSESSID=uuj599r4k1ohp48f1poobil665; expires=Sat, 28-Jan-2012 17:10:40 GMT; path=/
But the second request does not include this cookie, nor do any other ajax requests to that domain.
I am not trying to read the cookie for another domain, I just want the application on the other domain to be able to set and read its own cookie.
Is this possible?
I have tested in Chrome and Firefox 9.
回答1:
server should set header:
response.Headers.Add("Access-Control-Allow-Credentials", "true");
client set to:
xhrFields: { withCredentials: true }
回答2:
As long as you are using a browser which supports CORS, cookies on the AJAX request should work. But you must set withCredentials
on the XMLHttpRequest
to true.
See: The withCredentials attribute
I don't use JQuery but here's a question that deals specifically with setting withCredentials
via JQuery.
Sending credentials with cross-domain posts?
回答3:
No, cookies cannot be shared cross domain. The same origin policy could be circumvented for AJAX calls using the Access-Control-*
headers assuming the browser supports them, but for cookies there's no way.
回答4:
+Darin Dimitrov suspects that "the cookie is not saved by the browser because it comes from another domain than the one hosting the page which is at the origin of this call".
However, the cookie gets set as desired when using JSONP, but JSONP is only for GET requests.
My solution is to retrieve the cookie (a PHP session id) by loading the following php file in a <script>
:
<? echo $_GET['callback'] . '("' . session_id() . '")'; ?>
And to pass the session id as a request variable in all cross-domain POST requests.