我想用jquery ajax做一个跨域的xhr
我用的是一个特殊的库,可以让ie9支持跨域
http://cdnjs.cloudflare.com/ajax/libs/jquery-ajaxtransport-xdomainrequest/1.0.0/jquery.xdomainrequest.min.js
浏览器发送 xhr 但没有 cookies (Credentials)
以下代码在 http://first_domain.local 处运行
$.ajaxSetup({
type: "POST",
cache: false,
crossDomain: true,
data: {},
dataType: 'json',
xhrFields: {
withCredentials: true
}
});
jQuery.support.cors = true;
$.ajax({
cache: false,
async: true,
crossDomain: true,
url: "http://second_domain.local",
beforeSend: function(xhr) {
xhr.withCredentials=true;
},
type: "POST",
data: {},
dataType: "JSON",
success: function(res, textStatus, xhr) {
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
php 服务器上的设置:
$http_origin = $_SERVER['HTTP_ORIGIN'];
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Authorization');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Origin: '.$http_origin.'');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
它在 IE 10,11 friefox 和 chrome 中完美运行
回答:
关于这件事似乎有两种意见:
- 这是不可能的
- 使用 MoonScript 库
两者都是有效的,因为“无法在 IE9 和更早版本中发出跨域 ajax 请求并发送 cookie。”
但是! MoonScript(以某种方式)做到了这一点,它对我有用。
所以我建议你试试 MoonScript
最佳答案
- 跨源请求只能在 IE9 和更早版本中通过
XDomainRequest
实现,不能通过XMLHttpRequest
实现。您正在使用的库在这些浏览器中委托(delegate)给XDomainRequest
。 - 凭据跨源 ajax 请求在 IE9 和更早版本中是不可能的,因为
XDomainRequest
不支持它(不支持withCredentials
)。
关于javascript - ie9 ajax跨域withCredentials不发送cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23891207/