如何使用 jq 接收 blob 資料

JS菌發表於2019-04-25

20190418210256.png

如何使用 jq 接收 blob 資料

⭐️ 更多前端技術和知識點,搜尋訂閱號 JS 菌 訂閱

目前 jq 用的人還是挺多的,在一些簡單的促銷 h5 頁面,用 jq 去實現一些簡單的功能還是比較方便的。本文展示如何用 JQ 去請求一個 blob 物件的 img 圖片並渲染到頁面上 ?

預設 jq 的 ajax 物件中的 dataType 無法設定返回資源為 blob 那麼就需要手動設定,使其能夠最終請求一個 blob 物件

20190221102906.png

解決辦法:

使用原生 XMLHttpRequest

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()
複製程式碼

這種方法直接使用了原生的 ajax

另外還可以使用 xhr 或 xhrFields 配置來修改返回資源的型別

重寫 xhr

jq 的 ajax 方法提供了一個 xhr 屬性,可以自由定義 xhr

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 () {
    }
})
複製程式碼

修改 xhrFields

另外還可以修改 jq 的 ajax 方法中 xhrFields 屬性,定義響應型別為 blob

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 菌公眾賬號

請關注我的訂閱號,不定期推送有關 JS 的技術文章,只談技術不談八卦 ?

相關文章