ajaxでHTTPステータス:404等の取得

ajaxでサーバー自体につながらないは「404 Not Found」などで処理分岐させたい

作成日:2017-11-27, 更新日:2017-11-27

基本

エラー時で使う各情報
・「jqXHR.status」は、HTTPステータス
・「textStatus」は、エラー情報(timeout、error、parsererror等の文字列)
・「errorThrown」は、例外情報

▼jQuery1.6以上

$.ajax({
  url: 'http://〇〇〇/〇〇〇i',
  type:'〇〇〇',
  dataType: 'json',
}).done(function(data) {
  // 成功時の処理
}).fail(function(jqXHR, textStatus, errorThrown) {
  var codeJqXHR = parseFloat(jqXHR.status);
  if(codeJqXHR == 0 || jqXHR.status == 404 || errorThrown == 'Not Found') {
    console.log('There was a 404 error.'); 
  }
  else {
    $("#XMLHttpRequest").html("XMLHttpRequest : " + jqXHR.status);
    $("#textStatus").html("textStatus : " + textStatus);
    $("#errorThrown").html("errorThrown : " + errorThrown);
  }
}).always(function() {
  // 処理完了時(done()、fail()の後に入ってくる。)
});

▼jQuery1.6未満

$.ajax({
  url: 'http://〇〇〇/〇〇〇i',
  type:'〇〇〇',
  dataType: 'json',
  success: function(data) {
    // 成功時の処理
  },
  error: function(jqXHR, textStatus, errorThrown) {
    var codeJqXHR = parseFloat(jqXHR.status);
    if(codeJqXHR == 0 || jqXHR.status == 404 || errorThrown == 'Not Found') {
      console.log('There was a 404 error.'); 
    }
    else {
      $("#XMLHttpRequest").html("XMLHttpRequest : " + jqXHR.status);
      $("#textStatus").html("textStatus : " + textStatus);
      $("#errorThrown").html("errorThrown : " + errorThrown.message);
    }
  },
  complete : function(data) {
    // 処理完了時
  }
});