使用Ajax的Weather Underground API

我应该使用Ajax和JSON创建一个带有Weather Underground API的应用程序,但实际上没有太多关于如何去做的方向。 如果我能看到代码的完整版本,那么我就知道如何开始。 这就是我学习的方式。 我对JSON有点了解,但我不确定我的下一步是什么。

这是我的代码:

    Weather API App    

Your Awesome Forecast Page

Current Conditions

Your Hourly 1-day forecast

Your 7-day forecast

@charset "UTF-8"; /* CSS Document */ body{ font-family: Arial, Helvetica, sans-serif; background-color:darkblue; } #container{ width: 90%; margin: 0 auto; } /*Header ------------------------------*/ header { border-top-left-radius: 10px; border-top-right-radius: 10px; padding: 10px; background-color: rgba(255, 255, 255, 0.75); margin-bottom: 30px; } nav { padding: 0; margin: 0; } nav ul { padding: 0; margin: 0; padding-left: 10px; } nav li { display: inline-block; padding-left: 10px; } li a { text-decoration: none; color: black; font-weight: bold; } li a:hover { color: white; } .logo { width: 300px; margin: 0; display: inline-block; } h1 { display: inline-block; margin: 0; padding: 2%; }

main.js

 $.ajax({ url : "http://api.wunderground.com/api/ef5a156e62f050d2/conditions/q/OH/Columbus.json", dataType : "json", success : function(url) { var location = url['location']['city']; var temp_f = url['current_observation']['temp_f']; $(".conditions").html("Current temperature in " + location + " is: " + temp_f+"ºF"); } }); 

这是一个让你前进的开始。 您的AJAX函数返回JSON数据(打开您的控制台并查看)。 从JSON数据中检索任何特定键/值的正确方法如下所示,用于temp_f。 然后,就像您已经完成的那样,从您从JSON中提取的各种元素构建一个字符串,并将其写入您选择的HTML元素:

 $.ajax({ url: "http://api.wunderground.com/api/ef5a156e62f050d2/conditions/q/OH/Columbus.json", dataType: "json", success: function(url) { console.log(url); var location = 'Columbus'; var temp_f = url.current_observation.temp_f; $(".conditions").html("Current temperature in " + location + " is: " + temp_f + "ºF"); } }); 
  

我完全同意@ sideroxylon的回答,这只是一个旁注。

如果你只想要检索JSON数据,那么也值得探索使用$.getJSON函数,如果你不想担心你在$.ajax使用的数据类型,请参阅我的jquery下面的片段。


片段

 $(document).ready(function() { $.getJSON("https://api.wunderground.com/api/ef5a156e62f050d2/conditions/q/OH/Columbus.json", function(response) { var location = response['current_observation']['display_location']['city']; var temp_f = response['current_observation']['temp_f']; $(".conditions").html("Current temperature in " + location + " is: " + temp_f + "ºF"); console.log(response); }); });