美文网首页
FCC-JS-JQ-Get JSON with the jQue

FCC-JS-JQ-Get JSON with the jQue

作者: zhang_yongfeng | 来源:发表于2018-10-26 21:29 被阅读0次

当你需要根据服务器返回的数据来动态改变页面的时候,应用程序接口(API)就派上用场了。
记住,API——应用程序接口(Application Programming Interface)是计算机之间相互交流沟通的工具。
许多网站的应用程序接口(API)都是通过一种称为JSON格式的数据来传输的,JSON 是 JavaScript Object Notation的简写。
其实如果你曾经创建过JS对象的话,你就已经使用了这种数据格式,JSON是一种非常简洁的数据格式。
它通常表现为了两种形式,一种为单个对象,一种为多个对象
单个对象类似于:

{name:'盖伦',advantage:'单挑无敌'}
多个对象类似于:

[{name:'盖伦',advantage:'单挑无敌'},{name:'诺克',advantage:'上单霸主'}]
每个对象属性和属性值的组合就是我们经常听到的"键值对(key-value pairs)"。
让我们从之前的猫图API拿取数据吧。
你应该在你的点击事件中加入如下的代码:

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

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

});

在这之后,点击"Get Message"按钮。你的Ajax函数将把文字"The message will go here"替换成此从FreeCodeCam的猫图API中获得的原始JSON数据。
示例:

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

    $("#getMessage").on("click", function(){
      // 请把你的代码写在这条注释以下
      $.getJSON('/json/cats.json',function(json){
        $(".message").html(JSON.stringify(json))
      });
      // 请把你的代码写在这条注释以上
    });
  });
</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>


[{"id":0,"imageLink":"/images/funny-cat.jpg","codeNames":["Juggernaut","Mrs. Wallace","Buttercup"]},{"id":1,"imageLink":"/images/grumpy-cat.jpg","codeNames":["Oscar","Scrooge","Tyrion"]},{"id":2,"imageLink":"/images/mischievous-cat.jpg","codeNames":["The Doctor","Loki","Joker"]}]

相关文章

网友评论

      本文标题:FCC-JS-JQ-Get JSON with the jQue

      本文链接:https://www.haomeiwen.com/subject/smaltqtx.html