【问题标题】:Access-Control-Allow-Origin error when trying to get resources from site in same domain?尝试从同一域中的站点获取资源时出现 Access-Control-Allow-Origin 错误?
【发布时间】:2011-11-17 10:30:44
【问题描述】:

我只是想从服务器上的其他站点之一获取 html 并将其打印在当前站点上。这基本上就是我正在做的事情:

// The object
var xmlhttp = new XMLHttpRequest(); 

// When a button is pressed, we get the html
function printJSON(action)
{
    otherURL = "http://www.my.domain.com/other.php?action=" +action;

    xmlhttp.open('GET',otherURL,true);
    xmlhttp.send();
}

// and then print it in this div
xmlhttp.onreadystatechange = function
{
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
    {
        $('JSON_output').innerHTML = xmlhttp.responseText;
    }
}

我收到的错误是:

XMLHttpRequest 无法加载 http://www.my.domain.com/other.php?action=SEARCH。 Access-Control-Allow-Origin 不允许来源http://my.domain.com

这看起来很奇怪,因为这是服务器上的一个站点试图访问同一文件夹中的另一个站点。我的服务器有什么需要调整的吗?我需要设置 xmlhttp 中的属性吗?

干杯!

【问题讨论】:

    标签: javascript ajax cross-domain access-control


    【解决方案1】:

    根据the JavaScript same-origin policyhttp://www.my.domain.comhttp://my.domain.com 是两个不同的域(注意 www)。

    如果 www.my.domain.com 和 my.domain.com 指向同一个地方,最简单的解决方案是使otherURL 相对;以 "/other.php?action="; 开头这样,它将始终与您的页面位于同一域中。

    如果他们不指向同一个地方,则有一个更复杂的解决方案,涉及您的服务器输出名为Cross Origin Resource Sharing 的附加标头; here's an overview.

    【讨论】:

    • 你是个种马,谢谢。我不确定“域”到底意味着什么。现在我知道了,并且有一个工作站点!在一分钟内溢出将使我接受这个答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-15
    • 1970-01-01
    • 2017-12-16
    • 2017-12-29
    • 1970-01-01
    • 2015-11-05
    • 2017-03-03
    相关资源
    最近更新 更多