我有几个客户雇佣我来托管和维护他们的网站。为了方便我的工作,我添加了一个js,当他们不付钱给我的时候,我会把他们的网站放下来。现在我通过ftp手动完成。
*(通过css y将所有div显示为none)
这是页面上的js:
$(document).ready(function() {
getOutput();
});
function getOutput() {
getRequest(
'http://www.mypage.com/test.php',
drawOutput
);
return false;
}
function drawOutput(responseText) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = responseText;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(script, s);
}
function getRequest(url, success) {
var req = false;
try{
req = new XMLHttpRequest();
} catch (e){
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req .readyState == 4){
return req.status === 200 ?
success(req.responseText) : error(req.status)
;
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
这是php:
$array = array(
"test" => "up",
"test2" => "down",
"test3" => "down",
);
if(isset($_SERVER['HTTP_REFERER'])) {
$sitio = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST); //i get the url
$verifico = explode(".", $sitio); // divide the url
if ($verifico[0] == "www"){ //i check if it has www or not
$sitio = $verifico[1];
}
else {
$sitio = $verifico[0];
}
}
if ($array[$sitio] == "down"){
echo 'my.js';
}
这是php请求后打印的js代码:
$(document).ready(function() {
var jodita = '<style type="text/css">body,div{display:none!important;}</style>';
document.getElementsByTagName('head')[0].innerHTML = jodita;
});
这就是它的工作方式,js向php发出请求。php获取url并验证网站是否必须向上或向下,并根据结果返回js的url。我这样做是因为将来我可以在不接触所有网站的情况下更改第二个js。
当我在同一个域中使用它时,这很好,但当我使用不同的域时,会出现以下错误:
XMLHttpRequest无法加载http://domain.com/myfile.php.请求的资源上不存在"Access Control Allow Origin"标头。原点'http://www.theotherdomain.com因此不允许访问。
我尝试过一些解决方案,比如CORS,但它很难解决,我不明白。还有其他选择吗?
正如错误消息所说,您需要将Access-Control-Allow-Origin
标头添加到PHP脚本中:
//Allow Ajax requests from any domain
header("Access-Control-Allow-Origin: *");