【发布时间】:2017-08-24 21:13:00
【问题描述】:
我正在本地主机上运行一个 html 文件。我正在访问我服务器上的一个 php 文件。
Javascript 正在本地主机上运行:
var url = "http://www.chartmygolf.com/_TEST_DELETE/exclude.php";
var method = "GET";
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
if (!xhr) {
alert('CORS not supported');
return;
}
// Response handlers.
xhr.onload = function (data) {
var text = xhr.responseText;
alert('Response: ' + text);
};
xhr.onerror = function (data) {
alert('Woops, there was an error making the request.');
};
xhr.send();
我的服务器 www.mysite.com 上的 php:
<?php
$referrer = $_SERVER['HTTP_REFERER'];
$parts = parse_url($referrer);
$domain = $parts['host'];
header("Access-Control-Allow-Origin: http://" . $domain);
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
$arr = array("181K2", "4V419");
echo json_encode($arr);
?>
在 Chrome 和 Edge 中,它进入 alert('Woops, there was an error making the request.');
边缘错误:
SEC7120: Origin http://localhost:8080 not found in Access-Control-Allow-Origin header.
SCRIPT7002: XMLHttpRequest: Network Error 0x80700013, Could not complete the operation due to error 80700013.
Chrome 错误:
XMLHttpRequest cannot load http://www.chartmygolf.com/_TEST_DELETE/exclude.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
这让我发疯了。我已经尝试过 ajax,现在这种方法得到了不一致的结果。我已经在 stackoverflow 上阅读了大量线程,但没有一个答案有效。 (但是,这些线程似乎已经很久了。)
注意:如果我使用,我会得到同样的错误
header("Access-Control-Allow-Origin: *");
请帮忙。我失去了理智。
【问题讨论】:
标签: html xmlhttprequest cross-domain