LoginSignup
15
22

More than 5 years have passed since last update.

[Ajax] onreadystatechange の代わりに loadend イベントを使う

Posted at

onreadystatechange を使うのはやめようと思った

そもそも readyState ってなんだろう

AJAX The XMLHttpRequest onreadystatechange Event によれば、

XMLHttpRequest のステータスを保持する。0 から 4 までに変化する:
0: リクエストは初期化されていない
1: サーバ接続は確立した
2: リクエストを受信した
3: リクエストの処理中
4: リクエストは終了してレスポンスの準備が完了

だそうだ

そして、onreadystatechange は readyState 属性が変更されるたびに呼び出されたイベントハンドラを返す

つまり、onreadystatechange は一回の通信で何回も呼び出される可能性があるということ

なので普通は readyState の確認をするわけだ

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
  if(xhr.readyState === 4 && xhr.status === 200){
    console.log(xhr.response);
  }
}
xhr.open('GET', '/path/to/file', true);
xhr.send();

でも調べていくうちに load イベントとか error イベントとかあるじゃん。しかし、エラーなのに error でなく load が呼ばれることがあるそうで、loadend イベントならまとめて拾えるらしい

var xhr = new XMLHttpRequest();
xhr.addEventListener('loadend', function(){
  if(xhr.status === 200){
    console.log(xhr.response);
  }else{
    console.error(xhr.status+' '+xhr.statusText);
  }
});
xhr.open('GET', '/path/to/file', true);
xhr.send();

ってことでこれでOK?

参考

15
22
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
22