SYNCERのロゴ
アイキャッチ画像

XMLHttpRequestEventTarget.onprogress - ajax通信中に繰り返し発火するイベント

onprogressは、XMLHttpRequestEventTargetのイベントです。ajax通信中に繰り返しprogressイベントが発生し、ここに設定したコールバック関数が呼び出されます。

概要

名前
onprogress
所属
XMLHttpRequestEventTarget
イベント
progress
IDL
attribute EventHandler onprogress;

typedef EventHandlerNonNull? EventHandler;

callback EventHandlerNonNull = any (Event event);
仕様書
https://xhr.spec.whatwg.org/#handler-xhr-onprogress

チュートリアル

onprogressでイベントを設定する例です。

var xmlHttpRequest = new XMLHttpRequestEventTarget() ;
xmlHttpRequest.onprogress = function ( event ) {
	console.log( event ) ;
}

Event.addEventListener()でも、同様にイベントを設定できます。

xmlHttpRequest.addEventListener( "progress", function ( event ) {
	console.log( event ) ;
} ) ;

デモ

XMLHttpRequestEventTarget.onprogressのデモです。ボタンをクリックすると、ある画像をダウンロードします。

<!-- このコードは編集できます。 -->

<!DOCTYPE html>
<html>
<head>
<style>
body { word-break: break-all ; tab-size: 2 ; }
div#result { white-space: pre-wrap ; }
</style>
</head>
<body>
<p><button id="send">通信 [send()]</button></p>
<hr>
<img src="" id="hoge" width="120" height="auto">
<hr>
<div id="result"></div>
<script>
var xmlHttpRequest = new XMLHttpRequest() ;
xmlHttpRequest.responseType = "blob" ;

xmlHttpRequest.onloadstart = function ( event ) {
	appendText( "[loadstart] ダウンロードを開始しました!!" + "\n" ) ;
}

xmlHttpRequest.onprogress = function ( event ) {
	console.log( event ) ;
	appendText( "[progress] ダウンロード中…" + "\n" ) ;
}

xmlHttpRequest.onload = function ( event ) {
	appendText( "[load] ダウンロードが正常に完了しました!!" + "\n" ) ;
}

xmlHttpRequest.onloadend = function ( event ) {
	appendText( "[loadend] ダウンロードを終了しました!!" + "\n" ) ;
}

xmlHttpRequest.onerror = function ( event ) {
	appendText( "[error] ダウンロードに失敗しました…。" + "\n" ) ;
}

xmlHttpRequest.addEventListener( "load", function ( event ) {
	var blob = xmlHttpRequest.response ;
	var blobUrl = URL.createObjectURL( blob ) ;
	document.getElementById( "hoge" ).src = blobUrl ;
} ) ;

document.getElementById( "send" ).onclick = function () {
	xmlHttpRequest.open( "GET", "https://i.imgur.com/nyWu6oc.png?" + new Date().getTime() ) ;
	xmlHttpRequest.send() ;
}

function appendText ( text ) {
	document.getElementById( "result" ).appendChild( document.createTextNode( text ) ) ;
}
</script>
</body>
</html>

サポート状況

ChromeFirefoxSafariEdgeIEOperaiOS SafariAndroid
10+
  • Twitterでシェア
  • Facebookでシェア
  • Google+でシェア
  • はてなブックマークでシェア
  • pocketに保存
  • LINEでシェア
更新履歴
2017年10月20日 (金)
コンテンツを公開しました。