使用$.getJSON()取得JSON

 

語法:jQuery.getJSON( url [, data ] [, success ] )

其語法相等於如下

$.ajax({
    dataType: "json",
    url: url,
    data: data,
    success: success
});

 

1.success handler可為

<!DOCTYPE html>
<html>
<head>
    <script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
    <meta charset="utf-8">
    <title>JS Bin</title>
</head>
<body>
    <script>
        $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?&format=json", function (data) {
            var items = [];
            $.each(data, function (key, val) {
                items.push("<li id='" + key + "'>" + key + "</li>");
            });
            $("<ul/>", {
                "class": "my-new-list",
                html: items.join("")
            }).appendTo("body");
        });
    </script>
</body>
</html>

 

2.success handler也可藉由.done()來處理

<!DOCTYPE html>
<html>
<head>
    <script src="http://code.jquery.com/jquery-2.1.3.js"></script>
    <script>
        $(function () {
            var APIurl = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?&format=json";
            $.getJSON(APIurl).done(function (data) {
                $.each(data.items, function (i, item) {
                    $("<img/>").attr("src", item.media.m).appendTo("body");
                });
            });
        });
    </script>
</head>
<body>

</body>
</html>

說明:

先看APIurl的片段json內容為

{

  • "title":"Uploads from everyone",
  • "link":"http:\/\/www.flickr.com\/photos\/",
  • "description":"",
  • "modified":"2015-02-09T15:25:30Z",
  • "generator":"http:\/\/www.flickr.com\/",
  • "items":[
    1. {
      • "title":"Mini easel",
      • "link":"http:\/\/www.flickr.com\/photos\/128020934@N07\/15860763744\/",
      • "media":{
        • "m":"http:\/\/farm8.staticflickr.com\/7459\/15860763744_d908e33698_m.jpg"
        },
      • "date_taken":"2015-02-09T00:00:27-08:00",
      • "description":" <p><a href=\"http:\/\/www.flickr.com\/people\/128020934@N07\/\">krytheguy<\/a> posted a photo:<\/p> <p><a href=\"http:\/\/www.flickr.com\/photos\/128020934@N07\/15860763744\/\" title=\"Mini easel\"><img src=\"http:\/\/farm8.staticflickr.com\/7459\/15860763744_d908e33698_m.jpg\" width=\"240\" height=\"187\" alt=\"Mini easel\" \/><\/a><\/p> ",
      • "published":"2015-02-09T15:25:30Z",
      • "author":"nobody@flickr.com (krytheguy)",
      • "author_id":"128020934@N07",
      • "tags":""
      },
    2. {
      • "title":"Basis Peskens NIEUW.036",
      • "link":"http:\/\/www.flickr.com\/photos\/77695673@N04\/16483288865\/",
      • "media":{
        • "m":"http:\/\/farm9.staticflickr.com\/8650\/16483288865_360eac57e8_m.jpg"
        },
      • "date_taken":"2012-09-27T15:45:19-08:00",
      • "description":" <p><a href=\"http:\/\/www.flickr.com\/people\/77695673@N04\/\">Bakkerij Peskens<\/a> posted a photo:<\/p> <p><a href=\"http:\/\/www.flickr.com\/photos\/77695673@N04\/16483288865\/\" title=\"Basis Peskens NIEUW.036\"><img src=\"http:\/\/farm9.staticflickr.com\/8650\/16483288865_360eac57e8_m.jpg\" width=\"240\" height=\"135\" alt=\"Basis Peskens NIEUW.036\" \/><\/a><\/p> ",
      • "published":"2015-02-09T15:25:34Z",
      • "author":"nobody@flickr.com (Bakkerij Peskens)",
      • "author_id":"77695673@N04",
      • "tags":""
      }
    ]

}

當使用$.getJSON()完成之後,

我們就可以配合$.each()來對每一個object操作

 

3.可以附加data當作Query string

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>jQuery.getJSON demo</title>
    <style>
        img {
            height: 100px;
            float: left;
        }
    </style>
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

    <div id="images"></div>

    <script>
        (function () {
            var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
            $.getJSON(flickerAPI, {
                tags: "mount rainier",
                tagmode: "any",
                format: "json"
            })
              .done(function (data) {
                  $.each(data.items, function (i, item) {
                      $("<img>").attr("src", item.media.m).appendTo("#images");
                      if (i === 3) {
                          return false;
                      }
                  });
              });
        })();
    </script>

</body>
</html>

 

至於後端實作,可利用JsonResult將資料序列化成Json格式傳到前端

public ActionResult Details(int id)
{
    var speaker = _repository.FindSpeaker(id);
    return Json(speaker,
    JsonRequestBehavior.AllowGet);
}

 

參考資料:

jQuery.getJSON()

[ASP.NET]使用JQuery來傳遞JSON字串

[ASP.NET]使用JQuery來接收JSON字串

Utilities (第21項)-JSON.parse