从PHP跨域XML到Javascript

从PHP跨域XML到Javascript,javascript,php,xml,json,cross-domain,Javascript,Php,Xml,Json,Cross Domain,我想将XML数据从php(域A)发送到远程javascript文件(域B)。 我不能让它们在同一个域上,也不能在域B上有任何其他文件 我读过关于从php而不是XML发送JSONP对象的文章,但正如我从教程中了解到的,我需要一个php代理,它位于javascript文件所在的同一个域上。 (xhr.open(“GET”,“xmlproxy.php?url=“+escape(url),true);如果您控制输出可以使用的XML的php 默认情况下,Javascript只能打开加载域中的资源。其他资源

我想将XML数据从php(域A)发送到远程javascript文件(域B)。 我不能让它们在同一个域上,也不能在域B上有任何其他文件

我读过关于从php而不是XML发送JSONP对象的文章,但正如我从教程中了解到的,我需要一个php代理,它位于javascript文件所在的同一个域上。
(xhr.open(“GET”,“xmlproxy.php?url=“+escape(url),true);如果您控制输出可以使用的XML的php

默认情况下,Javascript只能打开加载域中的资源。其他资源必须允许Javascript在不同域中加载资源

为此,请在PHP脚本中添加一个标题:

header('Access-Control-Allow-Origin: http://javascript-domain.tld');
或允许从任何位置加载XML:

header('Access-Control-Allow-Origin: *');
您使用的是jQuery,如果您没有从PHP发送正确的内容类型,这里可能会出现问题

header('Content-Type: application/xml');
要验证阻止读取的是跨域,请在浏览器中打开Javascript控制台。它应输出错误消息。在Firefox中,类似于:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading 
the remote resource at http://domain.tld/path/to/resource. This can be fixed by 
moving the resource to the same domain or enabling CORS
如果您收到请求,它应该显示在开发人员工具的“网络”选项卡中,您可以验证HTTP响应头

下面是使用XHR的简单JS代码段,它强制使用内容类型:

var xhr = new XMLHttpRequest;
xhr.overrideMimeType("application/xml");
xhr.addEventListener(
  'load',
  function (xhr) {
    return function () {
      if (xhr.status >= 200 && xhr.status < 400) {
        console.log(xhr.responseXML);
      }
    }
  }(xhr)
);
xhr.open('GET', 'http://php-domain.tld/script.php');
xhr.setRequestHeader("Accept", "application/xml");
xhr.send();
var xhr=newxmlhttprequest;
重写emimetype(“应用程序/xml”);
xhr.addEventListener(
“加载”,
函数(xhr){
返回函数(){
如果(xhr.status>=200&&xhr.status<400){
console.log(xhr.responseXML);
}
}
}(xhr)
);
xhr.open('GET','http://php-domain.tld/script.php');
setRequestHeader(“接受”、“应用程序/xml”);
xhr.send();

JSONP不要求您使用代理…请告诉我们您需要传输多少数据?这很重要。想象一下,一个包含100首曲目的播放列表,每首曲目都有艺术家、曲目标题和持续时间。我无法准确估计数据块的大小,但这是我能想到的最接近的数据块大小。感谢您在t回复顺便说一句:我可以访问php和javascript文件,但我不能将任何其他文件添加到javascript所在的同一个域。我用代码示例编辑了我的问题,因为我无法使其工作。感谢您的帮助!不工作不是一个真正有用的错误描述。您需要调试不工作的内容。我添加了一些关于如何操作的信息。非常感谢!这个答案对我帮助很大。现在我需要为第二个域(php文件所在的域)获取ssl,它已经准备就绪(javascripts安全域不允许调用没有ssl的域)
Cross-Origin Request Blocked: The Same Origin Policy disallows reading 
the remote resource at http://domain.tld/path/to/resource. This can be fixed by 
moving the resource to the same domain or enabling CORS
var xhr = new XMLHttpRequest;
xhr.overrideMimeType("application/xml");
xhr.addEventListener(
  'load',
  function (xhr) {
    return function () {
      if (xhr.status >= 200 && xhr.status < 400) {
        console.log(xhr.responseXML);
      }
    }
  }(xhr)
);
xhr.open('GET', 'http://php-domain.tld/script.php');
xhr.setRequestHeader("Accept", "application/xml");
xhr.send();