ajax 提交 blob,使用jQuery的Ajax方法作为BLOB检索图像

这篇博客探讨了如何在不使用jQueryAjax的情况下,通过原生XMLHttpRequest获取并显示图片。示例代码展示了如何设置xhr.responseType为'blob'来处理图片数据,并在成功响应后将图片数据转换为URL并加载到页面上。此外,还提到jQuery3中同样可以实现此功能,提供了使用jQuery.ajax的两种方法来加载图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

您不能使用jQueryAjax,而是使用原生XMLHttpRequest。var xhr = new XMLHttpRequest();xhr.onreadystatechange = function(){

if (this.readyState == 4 && this.status == 200){

//this.response is what you're looking for

handler(this.response);

console.log(this.response, typeof this.response);

var img = document.getElementById('img');

var url = window.URL || window.webkitURL;

img.src = url.createObjectURL(this.response);

}}xhr.open('GET', 'http://jsfiddle.net/img/logo.png');xhr.responseType = 'blob';xhr.send();

编辑

因此,重新讨论这个主题,使用jQuery 3似乎确实是可行的。

jQuery.ajax({

url:'https://images.unsplash.com/photo-1465101108990-e5eac17cf76d?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ%3D%3D&s=471ae675a6140db97fea32b55781479e',

cache:false,

xhr:function(){// Seems like the only way to get access to the xhr object

var xhr = new XMLHttpRequest();

xhr.responseType= 'blob'

return xhr;

},

success: function(data){

var img = document.getElementById('img');

var url = window.URL || window.webkitURL;

img.src = url.createObjectURL(data);

},

error:function(){

}

});

使用xhrfield设置ResponseType

jQuery.ajax({

url:'https://images.unsplash.com/photo-1465101108990-e5eac17cf76d?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ%3D%3D&s=471ae675a6140db97fea32b55781479e',

cache:false,

xhrFields:{

responseType: 'blob'

},

success: function(data){

var img = document.getElementById('img');

var url = window.URL || window.webkitURL;

img.src = url.createObjectURL(data);

},

error:function(){

}

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值