【问题标题】:X-Requested-With is not allowed by Access-Control-Allow-HeadersAccess-Control-Allow-Headers 不允许 X-Requested-With
【发布时间】:2015-06-03 08:30:56
【问题描述】:

我正在开发一个系统。在该系统中,有一个将商品添加到购物车的功能。在该功能中,我使用的是 Jquery $.ajax。但是在线服务器我遇到了这个错误 -

"XMLHttpRequest 无法加载域 名称/add_to_cart.php?item_id=3&hotel_id=2。请求头域 Access-Control-Allow-Headers 不允许 X-Requested-With。"

谁能帮我解决这个错误。

我正在使用这个 jquery 代码

$(document).on('click', '.ordering_btn', function(){
    var item_id = $(this).data('value');
    var hotel_id = "<?php echo $hotel_id; ?>";

    $.ajax({
      type: 'GET',

      url: 'add_to_cart.php?item_id='+item_id+'&hotel_id='+hotel_id+'',

      contentType: 'text/plain',

      xhrFields: {
        withCredentials: false
      },

      headers: {
        "Access-Control-Allow-Headers": "X-Requested-With",
        "X-Requested-With": "XMLHttpRequest"        
      },

      success: function(data) {
        $('#cart_msg').css('display', 'none');
        $('#cart_item').html(data);
        console.log(data);
      },

      error: function() {
      }
    });
});

【问题讨论】:

  • 查看同源策略
  • 默认情况下,jQuery 不会为跨域请求发送 X-Requested-With 标头。你用的是什么代码?
  • 我正在使用这个 jquery 代码 - $(document).on('click', '.ordering_btn', function(){ var item_id = $(this).data('value'); var hotel_id = ""; $.ajax({ type: 'GET', url: 'add_to_cart.php?item_id='+item_id+'&hotel_id='+hotel_id+'', contentType: ' text/plain', xhrFields: { withCredentials: false }, headers: { }, success: function(data) { $('#cart_msg').css('display', 'none'); $('#cart_item' ).html(data); }, 错误: function() { } }); });
  • @MarkPreston — 编辑问题以将代码放入其中。使用 GUI 中的代码格式化按钮以确保其可读性。
  • @Mark Preston 链接到可能的相关问题:stackoverflow.com/questions/7564832/…

标签: javascript php jquery ajax cross-browser


【解决方案1】:

可以通过添加来修复错误

header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');

在 ajax 调用导致的服务器中......

【讨论】:

    【解决方案2】:

    删除这个:

      headers: {
        "Access-Control-Allow-Headers": "X-Requested-With",
        "X-Requested-With": "XMLHttpRequest"        
      },
    

    Access-Control-Allow-Headers响应 标头,而不是请求标头。

    您向其发出请求的服务器不允许X-Requested-With

    【讨论】:

    • 我按照您的指示操作,但收到此错误 - “XMLHttpRequest cannot load domainname/add_to_cart.php?item_id=2&hotel_id=1. The 'Access-Control-Allow-Origin' header contains multiple values ' *, *',但只允许一个。因此不允许访问 Origin 'Domain Name'。"
    • @MarkPreston — 太好了。这意味着你问的问题已经解决了,你有一个新的问题。 (即您向其发出请求的服务器被配置为发回无效的 CORS 响应)。
    猜你喜欢
    • 2017-03-03
    • 2015-06-17
    • 1970-01-01
    • 2016-11-30
    • 2016-11-24
    • 2020-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多