How can I use Json Jquery in api.openweathermap to get weather information

落爺英雄遲暮 提交于 2019-12-18 08:57:43

问题


I have this api

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

and I will get the information (name of city, weather...) using Jquery .

how I can do that ??


回答1:


Use an ajax call to get the JSON like this

$(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);
    });
});

Here's the fiddle: http://jsfiddle.net/cz7y852q/


If you do not want to use 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();

Use your own API key if the one in the URL does not work.




回答2:


Just issue ajax GET request:

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 implements CORS, which means that you will not have cross domain issues and can simply request API with AJAX.



来源:https://stackoverflow.com/questions/27336622/how-can-i-use-json-jquery-in-api-openweathermap-to-get-weather-information

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!