【问题标题】:PHP Header and Access-Control_Allow_Origin ErrorPHP 标头和 Access-Control_Allow_Origin 错误
【发布时间】:2013-02-13 19:23:20
【问题描述】:

我有两个域,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>

【问题讨论】:

  • 你为什么有echo "PHP Running";?删除它。在header() 呼叫之前,您不能回显任何内容。

标签: php javascript header cross-domain


【解决方案1】:

您正在授予来源为http://www.leobee.com 的页面从http://txtease.com/scriptExample.php 读取数据的权限,但您需要相反。

读取数据的权限必须来自数据来自的站点来自。站点不能授予自己从任意站点读取数据的权限。


echo "PHP Running"; 也会输出内容。有输出内容后不能调用header

【讨论】:

  • 我知道我需要将 php 标头 Access-Control_Allow_Origin 放在与 xml 文件相同的目录中。我应该删除 echo 语句。我对如何将 php 放入 xml 文件感到困惑。我收到错误消息,说 xml 装饰必须是 xml 文档中的第一个节点。我不明白如何在一次调用中运行 php 文件和 xml。
  • 通常的方法是给XML文件一个.php文件扩展名,然后把你的代码放在&lt;?php?&gt;之间。您还需要使用header('Content-Type: application/xml'); 告诉 PHP 输出正确的内容类型(默认为 HTML)。
猜你喜欢
  • 2017-01-09
  • 1970-01-01
  • 2019-10-22
  • 2017-09-20
  • 2017-11-30
  • 2018-09-19
  • 2021-12-02
  • 2015-09-28
  • 1970-01-01
相关资源
最近更新 更多