XMLHttpRequest.responseURL - レスポンスがあったURL
responseURLは、XMLHttpRequestのプロパティです。ajax通信で最終的にレスポンスがあったURLを返します。例えば、リクエスト先がリダイレクトした場合は、リダイレクト先のURLを返します。
概要
- 名前
- responseURL
- 所属
- XMLHttpRequest
- IDL
readonly attribute USVString responseURL;
- 仕様書
- https://xhr.spec.whatwg.org/#dom-xmlhttprequest-responseurl
説明
最終的にレスポンスを返したURLを返す。
readyStateがHEADERS_RECEIVED(2)以上の時に値が含まれる。
デモ
XMLHttpRequest.responseURLのデモです。ボタンをクリックすると、ある画像をダウンロードします。demo.phpにアクセスしますが、このファイルはimage.pngにリダイレクトします。取得できる値は、リダイレクト先のURLです。
<!-- このコードは編集できます。 -->
<!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 xhr = new XMLHttpRequest() ;
xhr.responseType = "blob" ;
xhr.onloadstart = function ( event ) {
appendText( "[loadstart] ダウンロードを開始しました!!" + "\n" ) ;
}
xhr.onprogress = function ( event ) {
appendText( "[progress] ダウンロード中…" + "\n" ) ;
}
xhr.onload = function ( event ) {
appendText( "[load] ダウンロードが正常に完了しました!!" + "\n" ) ;
}
xhr.onloadend = function ( event ) {
appendText( "[loadend] ダウンロードを終了しました!!" + "\n" ) ;
console.log( xhr ) ;
appendText( "responseURL: " + xhr.responseURL + "\n" ) ;
}
xhr.onerror = function ( event ) {
appendText( "[error] ダウンロードに失敗しました…。" + "\n" ) ;
}
xhr.addEventListener( "load", function ( event ) {
var blob = xhr.response ;
var blobUrl = URL.createObjectURL( blob ) ;
document.getElementById( "hoge" ).src = blobUrl ;
} ) ;
document.getElementById( "send" ).onclick = function () {
xhr.open( "GET", "./demo.php" ) ;
xhr.send() ;
}
function appendText ( text ) {
document.getElementById( "result" ).appendChild( document.createTextNode( text ) ) ;
}
</script>
</body>
</html>
サポート状況
Chrome | Firefox | Safari | Edge | IE | Opera | iOS Safari | Android |
---|---|---|---|---|---|---|---|
● 37+ | ● 32+ | ● 9.1+ | ● | × | ● 30+ | ● 9.1+ | × |
関連記事
- XMLHttpRequest.responseXML
- responseXMLは、XMLHttpRequestのプロパティです。レスポンスの内容をXMLDocumentで返します。
- panTo()
- 地図の位置座標を絶対的に移動する。
- XMLHttpRequest.statusText
- statusTextは、XMLHttpRequestのプロパティです。レスポンスのステータスのメッセージを返します。例えば、HTTP/1.1 200 OKの"OK"、HTTP/1.1 404 Not Foundの"Not Found"の部分です。ただし最近の、ステータスコードだけを返すサーバーの場合だと、メッセージ部分は空の文字列になります。
- XMLHttpRequest
- XMLHttpRequestは、ajax通信を管理するための機能を備えたインターフェイスです。