zilongxuan001 / LearnFreecode

0 stars 0 forks source link

Get JSON with the jQuery getJSON Method #307

Open zilongxuan001 opened 6 years ago

zilongxuan001 commented 6 years ago

介绍

你也能够从另外的地方获取信息,这里就是API发挥作用的地方。

大部分API把数据转换成JSON的形式。JSON表示JavaScript Object Notation,使用 Javascript语法来描述数据对象。

当你创造一个JavaScript对象时,你就使用了JSON。JSON不过就是对象属性和值,以及两边加上{}

这些属性和值被称为key-value pairs,键值对。

方法

让我们从CodeCamp's Photo API里获得JSON

这里是要放到click evnt的代码:

$.getJSON("/json/cats.json", function(json) {
  $(".message").html(JSON.stringify(json));
});

/json/cats.json是json的位置地址。

一旦你添加,点击Get Messagebutton,Ajax函数就替代The message will go there文本,变成从Free Code Camp Cat Photo API 获得的JSON数据。

代码


<script>
  $(document).ready(function() {

    $("#getMessage").on("click", function(){
      // Only change code below this line.

      $.getJSON("/json/cats.json",function(json){

        $(".message").html(JSON.stringify(json));
      });   

      // 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>

结果显示

image

点击按钮后,h获得所有的API信息,变成了 image

来源

https://www.freecodecamp.org/challenges/get-json-with-the-jquery-getjson-method

zilongxuan001 commented 6 years ago

20180402 image 分析后,如下

[
  {"id":0,
   "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":1,
    "imageLink":"https://s3.amazonaws.com/freecodecamp/grumpy-cat.jpg",
    "altText":"A white cat with blue eys, looking very grumpy. ",
    "codeNames":["Oscar","Scrooge","Tyrion"]},

   {"id":2,
    "imageLink":"https://s3.amazonaws.com/freecodecamp/mischievous-cat.jpg",
     "altText":"A ginger cat with one eye closed and mouth in a grin-like expression. Looking very mischievous. ",
     "codeNames":["The Doctor","Loki","Joker"]}
]