如何使用weather API创建我的天气HTML页面

时间:2014-06-15 16:53:44

标签: php css webpage weather weather-api

我想使用HTML和CSS编写页面代码。 我已经设计了它,但是因为我不知道如何将它与天气API链接以获取所选城市/国家的天气而丢失了。 任何人都可以举例说明代码是如何进行的吗?

1 个答案:

答案 0 :(得分:1)

您必须查看API文档,该文档应该告诉您如何从服务中请求数据。没有链接,我们无法帮助您。

This应该让您大致了解如何在PHP中使用JSON和API,但是如果您正在寻找一种简单的拉动机制来更新页面上的天气,那么您就不应该这样做。需要一些沉重的东西:它不需要服务器端。

我建议在这个上使用JavaScript,这将是这样的:

var req = new XMLHttpRequest();
var url = "yourURL"; //it is important that you read the API docs for this, because some APIs require you to use your API key in your request

req.open('GET', url, true);
req.onload = function (e) {
    if (req.readyState == 4 && req.status == 200) {
        if (req.status == 200) {
            var response = JSON.parse(req.responseText); //response is now an object containing all of the data that the API gives you; again, you'll have to look at the API docs to see how that information is formatted
            //update your page here using response data
            }
        }
    }
};
req.send(null);

我还建议完成How to use APIs with JavaScript

无论哪种方式,你都会得到一个JSON对象作为回报,其格式如下:

var response = [
    {
        "name": "Australia",
        "website": "http://www.footballaustralia.com.au",
        "foundedYear": 1961,
        "address": "Locked Bag A 4071\nNSW 1235\nSydney",
        "homeStadium": "ANZ Stadium",
        "stadiumCapacity": 83500,
        "group": "B",
        "groupRank": 3,
        "groupPoints": 0,
        "matchesPlayed": 1,
        "wins": 0,
        "losses": 1,
        "draws": 0,
        "goalsFor": 1,
        "goalsAgainst": 3,
        "goalsDiff": "-2",
        "id": "16EF7687-2D69-473C-BFE7-B781D67752DC",
        "type": "Team"
    }, 
    {
        "name": "England",
        "website": "http://www.thefa.com",
        "foundedYear": 1863,
        "address": "PO Box 1966\nSW1P 9EQ\nLondon",
        "homeStadium": "Wembley Stadium",
        "stadiumCapacity": 90000,
        "group": "D",
        "groupRank": 3,
        "groupPoints": 0,
        "matchesPlayed": 1,
        "wins": 0,
        "losses": 1,
        "draws": 0,
        "goalsFor": 1,
        "goalsAgainst": 2,
        "goalsDiff": "-1",
        "id": "2EFCFEB2-EBF8-4628-B659-B00C49D93811",
        "type": "Team"
    },
    {
        "name": "Ghana",
        "website": "http://www.ghanafa.org",
        "foundedYear": 1957,
        "address": "South East Ridge\n19338\nAccra",
        "homeStadium": "Ohene Djan Sports Stadium",
        "stadiumCapacity": 35000,
        "group": "G",
        "groupRank": 2,
        "groupPoints": 0,
        "matchesPlayed": 0,
        "wins": 0,
        "losses": 0,
        "draws": 0,
        "goalsFor": 0,
        "goalsAgainst": 0,
        "goalsDiff": "+0",
        "id": "CCC66F75-7004-46E4-BB31-259B06A42516",
        "type": "Team"
    }
];

因此,例如,您使用

访问澳大利亚的网站
response[0].website;

您也可以使用纯XML,但JSON是最常用的API请求方式。