【发布时间】:2018-12-02 13:35:06
【问题描述】:
我的 AJAX 函数:
function ajaxQuery(url, method, param, async, onsuccess, onfailure) {
var xmlHttpRequest = new XMLHttpRequest();
var callback = function(r) { r.status==200 ? (typeof(onsuccess)=='function' && onsuccess(r)) : (typeof(onfailure)=='function' && onfailure(r)); };
if(async) { xmlHttpRequest.onreadystatechange = function() { if(xmlHttpRequest.readyState==4) { callback(xmlHttpRequest); } } }
xmlHttpRequest.open(method, url, async);
xmlHttpRequest.setRequestHeader('X-REQUESTED-WITH', 'XMLHttpRequest');
xmlHttpRequest.withCredentials = true;
if(method == 'POST') { xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); }
xmlHttpRequest.send(param);
if(!async) { callback(xmlHttpRequest); }
}
函数调用:
ajaxQuery('http://example.net/index.php', 'GET', null, true, function(r) {
tmp.innerHTML = r.responseText;
nlt = [].map.call(tmp.querySelectorAll('.nlt'), function(x) { return x.textContent; });
});
在 PHP 中设置的标题:
header('Access-Control-Allow-Origin: https://example.com');
header('Access-Control-Allow-Origin: https://www.example.com');
header('Access-Control-Allow-Origin: http://example.net');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Credentials: true');
if(!preg_match('%https?:\/\/(www\.)?example\.com%', $_SERVER['HTTP_REFERER']) && !preg_match('%https?:\/\/example\.net%', $_SERVER['HTTP_REFERER'])) { die('No way!'); }
我从使用 https 的页面调用用户脚本,而我的域使用 http。当我通过 http 尝试 AJAX 时,我得到 (Firefox) Blocked loading mixed active content。如果我将查询 URL 切换为 https,则错误将更改为 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource,即使我的 PHP 脚本明确允许来自外部站点的请求。我错过了什么?
在这个特定示例中,我的网站是“http://example.net”,外部网站是“https://www.example.com”
【问题讨论】:
-
当你只使用
header('Access-Control-Allow-Origin: *');时它会起作用吗? -
@spielerds,不,它没有。相同的
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource错误。 -
这是整个错误信息?它也应该包含被阻止的域。可以? :)
-
@spielerds,被屏蔽的域是我的个人域 ("example.net/index.php")。出于匿名目的,我不会透露真实的域。
-
您可以访问外部站点吗?您可以更改该外部域的 CORS 政策吗?
标签: javascript php cors cross-domain