Javascript 如何将xhr请求转换为$http请求?
我正试图通过以下代码通过Javascript 如何将xhr请求转换为$http请求?,javascript,angularjs,ajax,Javascript,Angularjs,Ajax,我正试图通过以下代码通过ajax加载图像,这些代码已经在运行。我试图将其转换为angular$http,但它不起作用 普通ajax代码 var xhr = new XMLHttpRequest(); xhr.open('GET', attr.imageUrl, true); xhr.responseType = 'blob'; xhr.onload = function(e) { element[0].src = window.URL.createObjectURL(this.respo
ajax
加载图像,这些代码已经在运行。我试图将其转换为angular$http
,但它不起作用
普通ajax代码
var xhr = new XMLHttpRequest();
xhr.open('GET', attr.imageUrl, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
element[0].src = window.URL.createObjectURL(this.response);
};
xhr.send();
$http.get(attr.imageUrl, {}, {
responseType: 'arraybuffer'
})
.success(function(response) {
var file = new Blob([response]);
element[0].src = URL.createObjectURL(file);
});
角度代码
var xhr = new XMLHttpRequest();
xhr.open('GET', attr.imageUrl, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
element[0].src = window.URL.createObjectURL(this.response);
};
xhr.send();
$http.get(attr.imageUrl, {}, {
responseType: 'arraybuffer'
})
.success(function(response) {
var file = new Blob([response]);
element[0].src = URL.createObjectURL(file);
});
我认为应该是:
$http.get({ url: attr.imageUrl, responseType: 'arraybuffer'})
.success(function(response) {
var file = new Blob([response]);
element[0].src = URL.createObjectURL(file);
});
或:
试试这个:
$http.get(attr.imageUrl, {responseType: 'arraybuffer'})
.then(function(response) {
var file = new Blob([response]);
element[0].src = URL.createObjectURL(file);
});
试试这个-
$http.get(attr.imageUrl, {responseType: 'arraybuffer'})
.then(function(response) {
var file = new Blob([response.data], {
type: 'application/octet-binary'
});
element[0].src = URL.createObjectURL(file);
});
您的
响应
对象是什么样子的?Angular将响应放入response.data
这篇文章可能会有所帮助-第一个是$http.get(config)
第二个是$http.get(url,config)
区别在于你的参数,你有这样的:$http.get(attr.imageUrl,{},{responseType:'arraybuffer'})
,你不需要第二个参数{/code>