【问题标题】:How can I use Json Jquery in api.openweathermap to get weather information如何在 api.openweathermap 中使用 Json Jquery 获取天气信息
【发布时间】:2015-02-04 20:19:40
【问题描述】:

我有这个 api

 http://api.openweathermap.org/data/2.5/forecast/daily?q=Montpellier&mode=json&units=metric&cnt=10 

我将使用 Jquery 获取信息(城市名称、天气...)。

我怎么能做到这一点?

【问题讨论】:

    标签: jquery weather


    【解决方案1】:

    使用 ajax 调用来获取这样的 JSON

    $(document).ready(function(){
    $.getJSON("http://api.openweathermap.org/data/2.5/forecast/daily?q=Montpellier&mode=json&units=metric&cnt=10",function(result){
        alert("City: "+result.city.name);
        alert("Weather: "+ result.list[0].weather[0].description);
        });
    });
    

    这是小提琴:http://jsfiddle.net/cz7y852q/


    如果你不想使用 jQuery:

    var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
               if (xmlhttp.status == 200) {
                  var data = JSON.parse(xmlhttp.responseText);
                  //access json properties here
                  alert("Weather: "+ data.weather[0].description);
               }
               else if (xmlhttp.status == 400) {
                  alert('There was an error 400');
               }
               else {
                   alert('something else other than 200 was returned');
               }
            }
        };
        xmlhttp.open("GET", "http://api.openweathermap.org/data/2.5/weather?id=524901&APPID=7dba932c8f7027077d07d50dc20b4bf1", true);
        xmlhttp.send();
    

    如果 URL 中的 API key 不起作用,请使用您自己的 API key

    【讨论】:

    • 是的,但是我如何使用它显示城市名称和天气?
    • 没问题。乐于助人
    【解决方案2】:

    只需发出 ajax GET 请求:

    var url = "http://api.openweathermap.org/data/2.5/forecast/daily?q=Montpellier&mode=json&units=metric&cnt=10"
    
    $.getJSON(url).then(function(data) {
        console.log(data);
    });
    

    api.openweathermap.org 实现了 CORS,这意味着您不会有跨域问题,并且可以简单地使用 AJAX 请求 API。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-15
      • 1970-01-01
      • 1970-01-01
      • 2015-08-19
      • 2012-02-24
      • 2012-07-14
      • 2011-02-06
      • 2012-01-18
      相关资源
      最近更新 更多