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

XMLHttpRequest.responseURL - レスポンスがあったURL

responseURLは、XMLHttpRequestのプロパティです。ajax通信で最終的にレスポンスがあったURLを返します。例えば、リクエスト先がリダイレクトした場合は、リダイレクト先のURLを返します。

概要

名前
responseURL
所属
XMLHttpRequest
IDL
readonly attribute USVString responseURL;
仕様書
https://xhr.spec.whatwg.org/#dom-xmlhttprequest-responseurl

説明

最終的にレスポンスを返したURLを返す。

readyStateHEADERS_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>

サポート状況

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