【发布时间】:2017-03-30 02:51:14
【问题描述】:
假设我有域 a.com 和 b.com,并且我拥有这两个域。 b.com 上有一个名为 setcookie.aspx 的页面,在服务器代码中,它在 b.com 域下设置了一个 cookie。
我想从 a.com 向 b.com/setcookie.aspx 发出 HTTP 获取请求(b.com 已经允许来自 a.com 的 CORS 请求),如下所示:
$.get('http://www.b.com/setcookie.aspx');
由于某种原因,cookie 没有被设置。但是,如果我将 URL 放在隐藏的图像标签中:
然后就可以了。知道为什么 AJAX 请求没有设置 cookie 吗?
【问题讨论】:
-
$.get使用XMLHttpRequest- 阅读有关 cookie 的文档 here -XmlHttpRequest responses from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request, regardless of Access-Control- header values- 因此,您需要设置与withCredentials等效的 jQuery - 注意,您需要 jQuery 1.5.1+ 才能工作 - 你可能无法使用$.get- 改用$.ajax -
@JaromandaX 实际上较新的版本允许将设置对象传递给诸如
$.get和$.post之类的速记方法...但同意同样易于使用$.ajax -
@charlietfl - 我一定在文档中错过了!
-
将 withCredentials 设置为 true 有效,谢谢 :)
标签: javascript jquery asp.net ajax cookies