0

我制作了 .js 程序,它在我拥有的页面上制作baners(每个页面都发布在不同的服务器上)。我<script src="sample.com"></script>用来运行它。问题是,我的脚本请求主服务器(托管脚本的文件)获取一些变量,然后我收到消息:

Access-Control-Allow-Origin 不允许来源http://php.kotarbki.pl 。

我无法在我使用的服务器上打开 Access-Control-Allow-Origin,但这不是解决它的某种方法吗,我的意思是这个脚本托管在请求的服务器上!

-------------SERVER1---------------server-first.com---------------

script.js 文件:

var xmlhttp;
if (window.XMLHttpRequest)    {
   xmlhttp=new XMLHttpRequest();
}else{
   xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
   if (xmlhttp.readyState==4 && xmlhttp.status==200){
      return xmlhttp.responseText.split("#");
   }
}
xmlhttp.open("GET","http://server-first.com/page.php?action=getVariables",true);
xmlhttp.send();

page.php 文件:

if($_GET['action']=='getVariables'){
    echo $var1 . "#" . $var2;
}

-------------SERVER2---------------second-server.com---------------

<html>
<script src="server-first.com/script.js"></script>
</html>
4

2 回答 2

0

Your next recourse is likely going to be JSONP.

I typically don't use it, but here's the idea:

// dosomething.js -- script that's already on page
var doSomething = function (obj) {
    doStuff(obj);
};


// getdata.js script that's on another server
doSomething({ name : "...", id : 1234 });


var script = document.createElement("script"),
    parent = document.getElementsByTagName("script")[0].parentNode,
    src = "//otherserver.com/getdata.js";

script.src = src;
parent.appendChild(script);

You've now created another script file, set the source (where you can add whatever query data you want) and appended it to whatever element the first script element is a child of (usually head or body). When that script file loads, it's going to call doSomething() with whatever you put inside.

So to take this to its logical conclusion, you could either set your server to treat .js extensions as PHP (or selectively, if the file doesn't actually exist), or you could ask from the JavaScript side, for "//otherserver.com/getdata.php". Then, you'll have access from the php side to do whatever you need to do. Just echo back echo "doSomething(" . ... .");";.

You can accept a "callback" parameter in the query string, so that you can tell the file what the name of the function is that needs to fire on the JS page.

Also, you should make sure that your content-type header is set to javascript, rather than text or html, if you're going to use the .php extension.

于 2013-03-14T00:00:54.660 回答
0

如果域名不相同,则不能从一个站点向另一个站点发出请求。

于 2013-03-13T23:38:12.803 回答