在JS中如何發送ajax請求,並且解析后台返回的Blob類型數據,將數據轉換為文件導出,附帶兼容IE8等瀏覽器
普通的jQuery中的ajax請求后台,並不能處理Blob類型的數據,這里用的原生的XMLHttpRequest請求后台
var xhr = new XMLHttpRequest(); xhr.open("get", url, true); xhr.responseType = "blob"; xhr.onload = function() { if (this.status == 200) { var blob = this.response; if(blob.type == "text/html"){ tip("出錯"); return false } var fileName = filename; if(window.navigator.msSaveOrOpenBlob){ // IE瀏覽器下 navigator.msSaveBlob(blob, fileName); } else { var link = document.createElement("a"); link.href = window.URL.createObjectURL(blob); link.download = fileName; link.click(); window.URL.revokeObjectURL(link.href); } }else{ iframe.tip("請求錯誤!"); } } xhr.onloadend = function(res){ } xhr.send();
可參考:ajax處理流數據