XMLHttpRequest.abort() - 通信を中止する
abort()は、XMLHttpRequestのメソッドです。ajax通信を中止します。
概要
- 名前
- abort
- 所属
- XMLHttpRequest
- IDL
void abort();
- 仕様書
- https://xhr.spec.whatwg.org/#dom-xmlhttprequest-abort
説明
引数はありません。返り値もありません。
メソッドを実行すると、abortイベントが発生し、通信を終了します。XMLHttpRequestEventTarget.onabortでキャッチできます。
デモ
XMLHttpRequest.abort()のデモです。ボタンをクリックすると、ある画像をダウンロードします。通信を開始した直後にメソッドを実行します。
<!-- このコードは編集できます。 -->
<!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.abort() ;
}
xmlHttpRequest.onprogress = function ( 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.onabort = function ( event ) {
console.log( event ) ;
appendText( "[abort] ダウンロードを中止しました。" + "\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", "./image.png" ) ;
xmlHttpRequest.send() ;
}
function appendText ( text ) {
document.getElementById( "result" ).appendChild( document.createTextNode( text ) ) ;
}
</script>
</body>
</html>
サポート状況
Chrome | Firefox | Safari | Edge | IE | Opera | iOS Safari | Android |
---|---|---|---|---|---|---|---|
● | ● | ● | ● | ● | ● | ● | ● |
関連記事
- XMLHttpRequest.getAllResponseHeaders()
- getAllResponseHeaders()は、XMLHttpRequestのメソッドです。レスポンスヘッダーを全て取得します。
- XMLHttpRequest.status
- statusは、XMLHttpRequestのプロパティです。レスポンスのステータスコードを返します。
- XMLHttpRequest()
- XMLHttpRequest()は、XMLHttpRequestのコンストラクタです。新しいオブジェクトを作成します。
- XMLHttpRequest.send()
- send()は、XMLHttpRequestのメソッドです。ajax通信を実行します。