【问题标题】:Can not retrieve data between domain and sub domain无法在域和子域之间检索数据
【发布时间】:2016-08-04 10:49:33
【问题描述】:

我在 domian xyz.com 上有一个 Ajax 请求,我正在执行一个 来自 xyz.com 的 Ajax 请求从 abc.xyz.com 提取数据

var request = $.ajax({
        type: "POST",
        url: "https://abc.mno.com/vending/mainvending.php",
        data: {vlu:"1"},
        dataType: 'json',
        timeout: 10000,
        crossDomain: true,
        async: true,
        cache: false,               
        headers: { "cache-control": "no-cache" },
        error: function(  jqXHR, textStatus, errorThrown )
               { 
                    alert("error : " + errorThrown + " text :"+textStatus + " j :" +jqXHR.status);
                    // alert(jqXHR.responseText);
               },
        success: Succeeded,
        beforeSend: function( xhr ) { }
});

但我不断收到此错误,该错误已在浏览器 (Chrome) 中得到解决

XMLHttpRequest 无法加载 https://abc.xyz.com/vending/mainvending.php。预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段缓存控制。

mainvending.php中代码如下

<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
require_once 'vendors.php';

if(!empty($_POST)){
    /** Other codes follow **/
}else{
    /** Other codes follow **/
}
?>

我没有做什么或者我做错了什么?域名是 xyz,我从中检索数据的域是一个子域,这可能是问题所在,我该如何解决这个问题。

【问题讨论】:

    标签: javascript php html ajax cross-domain


    【解决方案1】:

    您的错误消息表明服务器不允许您发送缓存控制标头。

    你在这里做的:

    headers: { "cache-control": "no-cache" },
    

    …cache-control 是一个 response 标头,因此将其包含在请求中是没有意义的。

    删除该行。

    (或者,您可以将其添加到您已经设置的 Access-Control-Allow-Headers 标头中)。

    【讨论】:

    • 谢谢。没注意到。现在将删除问题
    【解决方案2】:

    你可以做以下两件事之一:-

    1. 从您的 AJAX 配置中删除此键值对

      headers: { "cache-control": "no-cache" },

    2. cache-control 标头添加到您的 PHP 代码以允许它。

      header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, cache-control');

    【讨论】:

      【解决方案3】:

      尝试设置这些标题

      header("Access-Control-Allow-Origin: *");
      header("Access-Control-Allow-Methods: PUT, GET, POST");
      header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
      

      【讨论】:

        猜你喜欢
        • 2023-03-09
        • 1970-01-01
        • 2013-08-31
        • 2016-12-27
        • 1970-01-01
        • 2021-10-09
        • 2016-08-16
        • 1970-01-01
        相关资源
        最近更新 更多