FreeCodeCamp - JSON APIs and Ajax

FreeCodeCamp - JSON APIs and Ajax

Trigger Click Events with jQuery

通过jQuery来绑定点击事件。

首先,我们来看一下函数 $(document).ready() 干了些什么。

这个函数中的代码只会在我们的页面加载时候运行一次,确保执行js之前页面所有的dom已经准备就绪。

任务:给"Get Message"按钮绑定一个点击事件。

我们先在$(document).ready()函数中增加一个click事件。代码如下:$(document).ready()function by adding this code:

$("#getMessage").on("click", function(){
});

<script>
  $(document).ready(function() {
    // Only change code below this line.
    $("#getMessage").on("click",function() {});
    // 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>

Change Text with Click Events

通过点击事件来更改文本。

当我们点击按钮时,我们可以更新HTML页面

任务:点击"Get Message"按钮,将class为message 的元素的文本改为:“Here is the message”。

为此在我们的点击事件中加入如下代码:

$(".message").html("Here is the message");

<script>
  $(document).ready(function() {
    $("#getMessage").on("click", function(){
      // Only change code below this line.
      $(".message").html("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>

Get JSON with the jQuery getJSON Method

当你需要根据服务器返回的数据来动态改变页面的时候,应用程序接口(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(){
      // 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>

Convert JSON Data to HTML

好了,我们已经从JSON API中获得了数据,现在把它们展现到我们的HTML页面中吧。

这里,我们使用.forEach()函数来循环遍历JSON数据写到htmll变量中。

首先我们定义一个HTML变量,
var html = "";

然后,我们使用.forEach()函数来循环遍历JSON数据写到html变量中,最后把html变量显示到我们的页面中。

整个过程的代码如下:

json.forEach(function(val) {
var keys = Object.keys(val);
html += "<div class = 'cat'>";
keys.forEach(function(key) {
​ html += "<b>" + key + "</b>: " + val[key] + "
";
});
html += "</div>
";
});

提示:示例中难点在于两个forEach循环,而且里面夹杂有字符串拼接,这是最头疼也最容易出错的地方。

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

    $("#getMessage").on("click", function() {
      $.getJSON("/json/cats.json", function(json) {

        var html = "";
        // Only change code below this line.
        json.forEach(function(val) {
          var keys = Object.keys(val);
          html += "<div class = 'cat'>";
          keys.forEach(function(key) {
            html += "<b>" + key + "</b>: " + val[key] + "<br>";
          });
          html += "</div><br>";
        });
        
        
        // Only change code above this line.

        $(".message").html(html);

      });
    });
  });
</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>

显示是这样的。

Render Images from Data Sources

从上节课获得的JSON数组中,每个对象都包含了一个以imageLink为键(key),以猫的图片的url为值(value)的键值对。

当我们在遍历这些对象时,我们用imageLink的属性来显示img元素的图片。

代码如下:

html += "<img src = '" + val.imageLink + "'>";

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

    $("#getMessage").on("click", function() {
      $.getJSON("/json/cats.json", function(json) {

        var html = "";

        json.forEach(function(val) {

          html += "<div class = 'cat'>";

          // Only change code below this line.
          
          html += "<img src= '"+val.imageLink+"'>"
          
          // Only change code above this line.

          html += "</div>";

        });

        $(".message").html(html);

      });
    });
  });
</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>

Prefilter JSON

如果我们不想把所有从JSON API中得到的图片都展现出来,我们可以在遍历之前做一次过滤。

我们把其中 "id" 键的值为1的图片过滤掉。

代码如下:

json = json.filter(function(val) {
return (val.id !== 1);
});

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

    $("#getMessage").on("click", function() {
      $.getJSON("/json/cats.json", function(json) {

        var html = "";

        // Only change code below this line.
        
        json = json.filter(function(val) {
          return (val.id !== 1);
        })
        
        // Only change code above this line.

        json.forEach(function(val) {

          html += "<div class = 'cat'>"

          html += "<img src = '" + val.imageLink + "'>"

          html += "</div>"

        });

        $(".message").html(html);

      });
    });
  });
</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>

Get Geolocation Data

我们还可以通过浏览器navigator获得我们当前所在的位置geolocation

位置的信息包括经度longitude和纬度latitude

你将会看到一个是否允许获取当前位置的提示。不管你选择允许或者禁止,只要代码正确,这关就能过了。

如果你选择允许,你将会看到右侧手机输出的文字为你当前所在位置的经纬度。

代码如下:

if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
​ $("#data").html("latitude: " + position.coords.latitude + "
longitude: " + position.coords.longitude);
});
}

<script>
  // Only change code below this line.
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      $("#data").html("latitude: " + position.coords.latitude + "<br>longitude: " + position.coords.longitude);
    });
  }
  
  
  // Only change code above this line.
</script>
<div id = "data">
  <h4>You are here:</h4>
  
</div>

效果如上。

(完)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,519评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,842评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,544评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,742评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,646评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,027评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,513评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,169评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,324评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,268评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,299评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,996评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,591评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,667评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,911评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,288评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,871评论 2 341

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,561评论 18 139
  • @转自GitHub 介绍js的基本数据类型。Undefined、Null、Boolean、Number、Strin...
    YT_Zou阅读 1,138评论 0 0
  • Address:https://www.zybuluo.com/XiangZhou/note/208532 Exp...
    天蠍蒗漫阅读 11,271评论 2 55
  • 易烊千玺,我爱他 他虽姓易,但却不容易
    璃沫叶落浅尝墨兮阅读 100评论 0 0
  • 今天是我主持中心会议,在开始之前我自己先进行梳理流程,接着通知人员准时开会,开会过程中我遵循紧凑的环节进行...
    如风_b235阅读 191评论 0 0