【发布时间】:2015-05-04 21:48:36
【问题描述】:
我正在尝试使用 AJAX 请求从另一个域获取图像的二进制数据。我尝试了各种方法,但没有有效的解决方案。我在互联网上发现了一些看起来不错的代码,但即使有这个调用我也会出错。
我做错了什么?有没有标准化的方法来做到这一点?
这是我到目前为止所尝试的:
var request = this.createCORSRequest('GET', 'http://url/to/image.png');
request.onload = function () {
var text = request.response;
};
request.onerror = function (error) {
alert('Woops, there was an error making the request.');
};
request.send();
private createCORSRequest(method, url) {
var xhr: XMLHttpRequest = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
var xdhr = new XDomainRequest();
xdhr.open(method, url);
} else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
return xhr;
}
我什至在 stackoverflow 上找到了这个没有 ajax 的解决方案,但它对我不起作用:
Asynchronously load images with jQuery
这里是错误事件包含的属性屏幕:
我的目标是从我从 atom feed 获得的 url 获取图像的二进制文件。我需要将图片复制到 MS SharePoint 的二进制文件。
【问题讨论】:
-
为避免 XY 问题,请描述您对图像的实际操作。您的代码中也没有 jQuery,但我看到了
private关键字。你用的是什么版本的JS? -
为了缩小问题的范围,您能否将您的
request.onerror函数替换为:request.onerror = function (error) { alert(error); };并在此处粘贴您收到的错误? -
如果你想使用纯ajax作为你提供的代码,你的图片URL需要在响应头后面附加
Access-Control-Allow-Origin。 -
@mplungjan 我使用打字稿,它编译为原生 javascript。它使用私有/公共的函数定义。我删除了 jQuery 关键字。将我的目标添加到我的问题中。
标签: javascript ajax cross-domain typescript