XMLHttpRequest 响应在 Javascript 中为 null
当尝试执行 XMLHttpRequest 时,响应从服务器返回(如在 Fiddler 中检查的那样),但 xhr.getAllResponseHeaders() 返回 null 并引发异常。
是因为“同源政策”吗?您能建议如何解决这个问题吗?
代码:使用datajs.codeplex.com开源代码:
xhr.onreadystatechange = function () {
if (xhr === null || xhr.readyState !== 4) {
return;
}
// Workaround for XHR behavior on IE.
var statusText = xhr.statusText;
var statusCode = xhr.status;
if (statusCode === 1223) {
statusCode = 204;
statusText = "No Content";
}
var headers = [];
var responseHeaders = xhr.getAllResponseHeaders().split(/\r?\n/);
资源位于不同的域中。访问 http://odata.netflix.com/v1/Catalog/Genres
when trying to execute XMLHttpRequest, the response is returned from server (as checked in Fiddler), but xhr.getAllResponseHeaders() returns null and throws exception.
Is it because of "Same Origin Policy"? Can you please suggest how to resolve the issue?
Code: Using datajs.codeplex.com open source code:
xhr.onreadystatechange = function () {
if (xhr === null || xhr.readyState !== 4) {
return;
}
// Workaround for XHR behavior on IE.
var statusText = xhr.statusText;
var statusCode = xhr.status;
if (statusCode === 1223) {
statusCode = 204;
statusText = "No Content";
}
var headers = [];
var responseHeaders = xhr.getAllResponseHeaders().split(/\r?\n/);
Resource is located in different domain. Accessing http://odata.netflix.com/v1/Catalog/Genres
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要规避同源策略,您可以使用 JS 调用 PHP 脚本来获取外部 url 的内容并
echo
结果。To circumvent the same-origin policy you could use JS to call a PHP script that gets the contents of the external url and
echo
the results.如果同源策略是您的问题,您可以使用 YQL 作为代理。
编辑:例如。 http://developer.yahoo.com/yql/console/#h=select%20*%20from%20atom%2810%29%20where%20url %3D%27http%3A//odata.netflix.com/v1/Catalog/Genres%27
好处是,您可以要求以 json 形式获取结果,并从客户端脚本轻松使用它。
If the The same-origin policy is your problem, you could use YQL as a proxy.
EDIT: eg. http://developer.yahoo.com/yql/console/#h=select%20*%20from%20atom%2810%29%20where%20url%3D%27http%3A//odata.netflix.com/v1/Catalog/Genres%27
What's nice is that you can ask to get the result as json and consume it easily from your client script.