天天看點

FCC - JSON APIs and Ajax

之前所有的HTML和CSS的内容都是靜态的頁面,所有的内容部分都需要前端人員在寫網頁的時候填寫好,比如我們之前做的portfolio和tribute page。這豈不是超級麻煩的!要知道我們一個html寫出來的頁面可以特别長,一層套一層的div,是以人為去修改很費力,而且容易出錯。接下來要學習的内容就是如何讓我們的内容是自動填充到html當中去。We’ll learn how to update HTML with the data we get from these APIs using a technology called Ajax.

  1. 複習一下在jQuery的學習筆記中提到過的,$(document).ready()函數,它實在頁面加載完成後運作一次。
  2. Adding a “click on” function on the getMessage button to change the text in message class element into ready function.
<script>
  $(document).ready(function() {
    $("#getMessage").on("click", function(){
      // Only change code below this line.
      $(".message").text("Here is the message");
      // Only change code above this line.
    });
  });
</script>


<div class="container-fluid">
  <div class = "row text-center">
    <h2>Cat Photo Finder</h2>
  </div>
  <div class = "row text-center">
    <div class = "col-xs-12 well message">
      The message will go here
    </div>
  </div>
  <div class = "row text-center">
    <div class = "col-xs-12">
      <button id = "getMessage" class = "btn btn-primary">
        Get Message
      </button>
    </div>
  </div>
</div>
           
  1. 接下來正式開始簡單的json api介紹,首先$.getJSON(), Load JSON-encoded data from the server using a GET HTTP request. 這個函數有三個可填的參數,第二個可選的是一個回調函數類型的參數,這個回調函數會在json從伺服器上成功下載下傳之後運作。回調參數中的第一個參數就是已經解析好的json檔案。例子:

    首先我們的json檔案是這樣的話:

[
  {
    "id": ,
    "imageLink": "https://s3.amazonaws.com/freecodecamp/funny-cat.jpg",
    "altText": "A white cat wearing a green helmet shaped melon on it's head. ",
    "codeNames": [
      "Juggernaut",
      "Mrs. Wallace",
      "Buttercup"
    ]
  },
  {
    "id": ,
    "imageLink": "https://s3.amazonaws.com/freecodecamp/grumpy-cat.jpg",
    "altText": "A white cat with blue eys, looking very grumpy. ",
    "codeNames": [
      "Oscar",
      "Scrooge",
      "Tyrion"
    ]
  }
]
           

那麼這個回調函數首先通過數組的forEach函數将json中的數組周遊,在每一個數組元素的周遊中,又利用jQuery的.each函數将這個數組元素,實際上是一個object的每一個鍵值對周遊,輸出到html這個最開始定義好的變量當中。當所有周遊完成後就将html的内容寫到.message的這個div當中。

<script>
  $(document).ready(function() {
    $("#getMessage").on("click", function() {
      $.getJSON("/json/cats.json", function(json) {
        var html = "";
        json.forEach(function(val) {
          html += "<div class = 'cat'>";
          $.each( val, function( key, val ) {
            html += "<strong>" + key + "</strong>: " + val + "<br>";
          });
          html += "</div><br>";
        });
        $(".message").html(html);
      });
    });
  });
</script>
           

下面這個的功能稍有不同,它在周遊每一個數組元素的時候隻關心這個元素當中的imageLink和altText這兩個鍵值對,是以它沒有用.each去周遊所有元素的鍵值對,而是直接用val[“imageLink”]這種方式直接通路這個object。

<script>
  $(document).ready(function() {
    $("#getMessage").on("click", function() {
      $.getJSON("/json/cats.json", function(json) {
        var html = "";
        json.forEach(function(val) {
          html += "<div class = 'cat'>";
          html += "<img src = '" + val["imageLink"] + "' alt = " + val["altText"] + "'>";
          html += "</div>";
        });
        $(".message").html(html);
      });
    });
  });
</script>