iT邦幫忙

0

使用XMLHttpRequest 將圖片轉成blob ,無法使用同步去執行

  • 分享至 

  • twitterImage

問題如題:使用XMLHttpRequest 將圖片轉成blob ,無法使用同步去執行
小弟有找到使用ajax的方式執行同步,是可以的,只是看了很多資料還是搞不懂為何XMLHttpRequest無法執行同步(xhr.open('POST', image, false))

 <script type="text/javascript">
		blob('images/01.jpg');
        function blob(image){
			//建立XMLHttpRequest物件
			var xhr = new XMLHttpRequest();
			//配置請求方式、請求地址以及是否同步
			xhr.open('POST', image, true);
			//設定請求結果型別為blob
			xhr.responseType = 'blob';
			//請求成功回撥函式
			xhr.onload = function(e) {
				if (this.status == 200) {//請求成功
					//獲取blob物件
					var blob = this.response;
					//獲取blob物件地址,並把值賦給容器
					document.getElementById("video").src = URL.createObjectURL(blob);
				}
			};
			xhr.send();
		}
    </script>
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
淺水員
iT邦大師 6 級 ‧ 2020-12-22 16:22:18
最佳解答

參考MDN:Synchronous and asynchronous requests
所以你要的也許是這樣

var xhr = new XMLHttpRequest();
//配置請求方式、請求地址以及是否同步
xhr.open('POST', image, false);
//設定請求結果型別為blob
xhr.responseType = 'blob';
xhr.send();
if (xhr.status == 200) {//請求成功
    //獲取blob物件
    var blob = xhr.response;
    //獲取blob物件地址,並把值賦給容器
    document.getElementById("video").src = URL.createObjectURL(blob);
}

firefox 測試出現

因為會影響使用者的使用體驗,已棄用主執行緒中的同步 XMLHttpRequest。若需更多資訊請參考 http://xhr.spec.whatwg.org/

chrome 測試出現

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/

儘管有跑出預計的結果,但建議還是用非同步處理吧

我要發表回答

立即登入回答