【问题标题】:ie9 ajax cross domain withCredentials not sending cookieie9 ajax跨域withCredentials不发送cookie
【发布时间】:2014-07-16 11:19:24
【问题描述】:

我想用 jquery ajax 做一个跨域 xhr
我正在使用一个特殊的库,它允许 ie9 支持跨域
http://cdnjs.cloudflare.com/ajax/libs/jquery-ajaxtransport-xdomainrequest/1.0.0/jquery.xdomainrequest.min.js

浏览器发送 xhr 但没有 cookie(凭据)
以下代码运行在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 中完美运行

回答:

关于这件事似乎有两种意见:

  1. 这是不可能的
  2. 使用 MoonScript 库

两者都有效,因为“没有办法在 IE9 及更早版本中发出跨域 ajax 请求并发送 cookie。”

但是! MoonScript 做到了(不知何故),它对我有用。

所以我建议你试试 MoonScript

【问题讨论】:

    标签: javascript internet-explorer cookies internet-explorer-9 cross-domain


    【解决方案1】:
    1. 只能通过XDomainRequest 在IE9 和更早版本中进行跨源请求,而不是通过XMLHttpRequest。在这些浏览器中,您使用的库代表XDomainRequest
    2. 在 IE9 和更早的版本中不可能有凭据的跨域 ajax 请求,因为XDomainRequest 不支持这个(不支持withCredentials)。

    【讨论】:

      【解决方案2】:

      如果您使用 jquery $.ajax,有一个完美的解决方案 只需包含“MoonScript”JQuery ajax-transport 就可以了! https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest

      【讨论】:

      • 不是问题的解决方案,不知道为什么会这样标记。 没有 方法可以在 IE9 和更早的版本中发出跨域 ajax 请求发送 cookie。没有图书馆可以做到这一点,因为图书馆必须使用XDomainRequest,这不允许cookie (among other things) 与请求一起发送。
      • 阅读链接中的信息,它对我有用。 “在 jQuery 1.5+ 中使用 $.ajax 函数时,使用 IE8 和 IE9 的 XDomainRequest 对象实现自动跨域资源共享支持。”
      • 您的问题询问如何发送 cookie。这个答案不是您实际问题的解决方案。也许你应该更新你的问题?
      猜你喜欢
      • 2014-03-17
      • 2021-03-05
      • 1970-01-01
      • 2020-06-30
      • 2012-06-09
      • 2019-02-11
      • 2013-01-05
      • 1970-01-01
      • 2012-12-06
      相关资源
      最近更新 更多