我有两个域,leobee.com 和 txtease.com。我想将 leobee.com 中的 xml 脚本加载到 txtease.com 上的 php 页面中。通过研究 stackoverflow 站点,我能够获得创建以下脚本的信息,但是,我没有看到如何解决此问题。
我已将 php 标头添加到请求脚本中,但出现“Access-Control-Allow-Origin 不允许来源”错误。
你能看看我的剧本,让我知道我哪里出错了吗?测试脚本位于: http ://txtease.com/crossdomain/scripts/example.html
在 chrome/ 或 firebug 控制台中使用: createCORSRequest('GET', ' http://www.leobee.com/crossdomain/data/data.xml ');
PHP 脚本:
<?php
echo "PHP Running";
header('Access-Control-Allow-Origin: http://www.leobee.com');
?>
<script>
var xhr = new window.XMLHttpRequest();
var string;
function createCORSRequest(method, url) {
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
xhr.send(null);
string ="with Credentials";
xhr.onerror = function() {console.log('There was an error!')};
xhr.onreadystatechange = callbackFunction(string);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
xhr.send(null);
string ="x domain request";
xhr.onreadystatechange = callbackFunction(string);
} else if(!"withCredentials" in xhr){
xhr.open(method, url, true);
xhr.send(null);
string ="with no Credentials";
xhr.onreadystatechange = callbackFunction(string);
}else {
// Otherwise, CORS is not supported by the browser.
alert("cross domain not supported");
xhr = null;
}
return xhr;
}
function callbackFunction(string){
console.log("Responding function: "+string);
if (xhr.readyState == 4){
var responseText = xhr.responseXML;
console.log("xml string is: "+responseText);
if (xhr.responseXML ===null){
responseText=xhr.responseText;
console.log("html string is: "+responseText);
}
}
}
</script>