您的当前位置:首页正文

JSON API-FreeCodeCamp

来源:华拓网

这部分主要介绍了两个功能,获取json数据和获取位置,jquery现在用的越来越少,这段大概看下就可以过了

  1. convert json to html
<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(m){
          var k = Object.keys(m);
          html+="<div class = 'cat'>";
          k.forEach(function(k){
            html+="<strong>"+k+"</strong>:"+m[k]+"<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>
  1. access user's location
    Every browser has a built in navigator that can give us this information.
if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
            $("#data").html("latitude: " 
                             + position.coords.latitude + "<br>longitude: " 
                             + position.coords.longitude); 
      });
}