javascript - 将天气 API 与 JSON 和 JavaScript/jQuery 结合使用

标签 javascript jquery json weather-api openweathermap

我发现了这个免费的天气 API,当您发送 HTTP GET 请求时,它会为您提供天气预报 - 预报以 JSON 格式传递。请求可能如下所示:

Examples of JSON format:
Seaching by city name: api.openweathermap.org/data/2.5/weather?q=London,uk
Seaching by geographic coordinats: api.openweathermap.org/data/2.5/weather?lat=35&lon=139 Seaching by city ID: api.openweathermap.org/data/2.5/weather?id=2172797

因此,您返回的响应显然是由 url 末尾定义的,其中包含一些变量。

我发现您可以使用 jQuery 函数 getJSON() 从通过 HTTP GET 请求获得的文本文件中创建一个对象,您还可以使用变量来更改 url。举个例子:

var person = "john";
$.getJSON("https://graph.facebook.com/" + person, function(person){

    $.each(person, function(key, value){
        document.write(key+": "+value+"<br />"); 
    });
}); 

给出输出

id: 779695190
first_name: John
gender: male
last_name: Chan
locale: en_US
name: John Chan
username: John


但是,当我尝试将其与天气 API 一起使用时,它不起作用 - 没有输出。 (为了简单起见,这里没有 url 变量。)下面的代码是我认为的完成方式(但显然不是)。

$.getJSON("api.openweathermap.org/data/2.5/weather?q=London,uk", function(forecast){
    var temperature = forecast.main.temp;
    document.write(temperature);
});

在此处查看预测的 JSON 结构:http://bugs.openweathermap.org/projects/api/wiki/Weather_Data

所以基本上我的问题是:我如何将 url 变量附加到weather-api-urls(并确保请求可以是城市名称或坐标)?从服务器获取检索到的数据后,我将如何访问它?

最佳答案

首先,您可以读取纬度和经度值或邮政编码或城市 ID,然后可以通过调用包含 ajax 的函数来附加它们,以调用 api wrt 给定参数。请参阅下面,我已经尝试过使用它来自浏览器的经纬度值。获得结果后,您可以像任何其他 json 对象一样访问它们。

function success(position) {
    var lat = position.coords.latitude;
    var long = position.coords.longitude;
    var timstp = position.timestamp;
    var myDate = new Date(timstp).toLocaleString();
    //console.log("Lat="+lat+"Long="+long+"timstp="+timstp+"date="+myDate); 

    $.ajax({
      url: "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + long + "&appid=690660b930904f0cee1975853d5a2375",
      dataType: 'jsonp',
      success: function(results) {
        console.log(results);

   
      }
    });
}

关于javascript - 将天气 API 与 JSON 和 JavaScript/jQuery 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23456886/

相关文章:

jquery 检查 xml 元素是否有子元素?

javascript - jQuery($(this).parent() 发现不起作用

python - 在 Python 中生成 JSON 模式

javascript - 遍历嵌套的 json 对象数组

javascript - CSS 绑定(bind)在 Knockout JS 中不起作用

javascript - .NET Core 2 端点不会在 POST 上绑定(bind) FromBody 的参数

javascript - Puppeteer 查询选择器 - 如何获得第二个匹配项

javascript - 为什么我的网页在移动设备上滚动不稳定,但在笔记本电脑上滚动正常

javascript - 数据表数据优先级/列优先级

json - 如何从本地 JSON 更新标签和 UIImage 占位符?