⭐️ 更多前端技术和知识点,搜索订阅号
JS 菌
订阅前端
目前 jq 用的人仍是挺多的,在一些简单的促销 h5 页面,用 jq 去实现一些简单的功能仍是比较方便的。本文展现如何用 JQ 去请求一个 blob 对象的 img 图片并渲染到页面上 👀web
默认 jq 的 ajax 对象中的 dataType 没法设置返回资源为 blob 那么就须要手动设置,使其可以最终请求一个 blob 对象ajax
var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
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', 'https://httpbin.org/image/png')
xhr.responseType = 'blob'
xhr.send()
复制代码
这种方法直接使用了原生的 ajaxui
另外还能够使用 xhr 或 xhrFields 配置来修改返回资源的类型this
jq 的 ajax 方法提供了一个 xhr 属性,能够自由定义 xhrurl
jQuery.ajax({
url: 'https://httpbin.org/image/png',
cache: false,
xhr: function () {
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 () {
}
})
复制代码
另外还能够修改 jq 的 ajax 方法中 xhrFields 属性,定义响应类型为 blobspa
jQuery.ajax({
url: 'https://httpbin.org/image/png',
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 () {
}
})
复制代码
请关注个人订阅号,不按期推送有关 JS 的技术文章,只谈技术不谈八卦 😊code