LoginSignup
0
1

More than 5 years have passed since last update.

jQuery.getJSON でファイルがない時の処理

Posted at

jQuery.getJSON でファイルがないのを明示する方法です。
.fail がポイントです。

ファイルがあった場合
success_jquery.png

ファイルがなかった場合
fail_jquery.png

html ファイル

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Cache-Control" content="no-cache" />
<meta http-equiv="CONTENT-TYPE" content="text/html; charset=utf-8" />
<script src="/js/jquery-3.3.1.min.js"></script>
<script src="example_json.js"></script>
<title>example_json</title>
</head>
<body>
<h2>example_json</h2><p />
<div class="contents">contents</div>
<hr />
Jul/24/2018 AM 08:25<p />
</body>
</html>
example_json.js
// -----------------------------------------------------------------------
//  example_json.js
//
//                  Jul/24/2018
//
// -----------------------------------------------------------------------
jQuery (function ()
{
    jQuery("#outarea_aa").text ("*** example_json *** start ***")

    var data_text = ""

//  var file_in = "./tochigi.json"
    var file_in = "./cities.json"

    jQuery.getJSON (file_in,function (data_aa)
        {
        var str_out = ""
        str_out += "<table>"
        for (var key in data_aa)
            {
            str_out += "<tr>"
            str_out += "<td>" + data_aa[key].name + "</td>"
            str_out += "<td>" + data_aa[key].population + "</td>"
            str_out += "<td>" + data_aa[key].date_mod + "</td>"
            str_out += "</tr>"
            }
        str_out += "</table>"

        jQuery(".contents").html (str_out)
        })
        .fail(function(jqXHR, textStatus, errorThrown)
            {
            var str_out = "<h2>Not Exist</h2>"
            str_out += "<blockquote>"
                str_out += file_in + "<br />"
            str_out += "</blockquote>"
            jQuery(".contents").html(str_out)
            jQuery("#outarea_ee").text("textStatus = " + textStatus)
            })

    jQuery("#outarea_hh").text ("*** example_json *** end ***")
})

// -----------------------------------------------------------------------

サンプルのJSON ファイル

cities.json
{
  "t0921": {
    "name": "宇都宮",
    "population": 68714,
    "date_mod": "1950-9-24"
  },
  "t0922": {
    "name": "小山",
    "population": 29157,
    "date_mod": "1950-3-15"
  },
  "t0923": {
    "name": "佐野",
    "population": 65741,
    "date_mod": "1950-10-7"
  },
  "t0924": {
    "name": "足利",
    "population": 38164,
    "date_mod": "1950-6-22"
  },
  "t0925": {
    "name": "日光",
    "population": 49675,
    "date_mod": "1950-8-28"
  },
  "t0926": {
    "name": "下野",
    "population": 65813,
    "date_mod": "1950-9-12"
  }
}
0
1
0

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
0
1