试图从同一域中的站点获取资源时出现访问-控制-允许-起源错误

Access-Control-Allow-Origin error when trying to get resources from site in same domain?

本文关键字:访问 控制 错误 起源 允许 资源 获取 站点      更新时间:2023-09-26

我只是想从服务器上的其他站点之一抓取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不允许Origin http://my.domain.com

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

干杯!

http://www.my.domain.com和http://my.domain.com根据JavaScript同源策略是两个不同的域(注意www)。

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

如果没有,指向同一个地方,有一个更复杂的解决方案,涉及到你的服务器输出额外的头,称为跨源资源共享;