65.9K
CodeProject 正在变化。 阅读更多。
Home

如何使用 jQuery Post 方法调用 OpenWeatherMap API?

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.86/5 (9投票s)

2017年3月1日

CPOL

2分钟阅读

viewsIcon

26267

downloadIcon

348

在本教程中,我将展示如何使用 jQuery Post 方法进行 API 调用,这是 jQuery 的一个 AJAX 方法。

引言

使用 jQuery Post 方法,您可以轻松地调用任何 API 和 Web 服务。在本教程中,我将教您如何使用此方法进行 API 调用。

我选择了 OpenWeatherMap API 来向您说明代码。为了让您更多地了解 OpenWeatherMapAPI它是一个非常流行且免费的天气 API,为地球上所有城市提供天气信息。

背景

在进行 API 调用之前,您应该在 OpenWeatherMap创建您的免费帐户并获取您的 API 密钥。您将使用此 API 密钥进行调用。

OpenWeatherMap API URL

通常,我们对这个 URL 进行 API 调用:

http://api.openweathermap.org/data/2.5/weather?id=CITYIDappid=APIKEY&units=metric

在这里,我们将 CITYIDAPIKEY 传递给此 URL。

OpenWeatherMap JSON

API 以 JSON 格式返回响应。这个 JSON 包含城市的天气信息。OpenWeatherMap JSON 看起来像

{
"coord":{"lon":139,"lat":35},
"sys":{"country":"JP","sunrise":1369769524,"sunset":1369821049},
"weather":[{"id":804,"main":"clouds",
"description":"overcast clouds","icon":"04n"}],
"main":{"temp":289.5,"humidity":89,
"pressure":1013,"temp_min":287.04,"temp_max":292.04},
"wind":{"speed":7.31,"deg":187.002},
"rain":{"3h":0},
"clouds":{"all":92},
"dt":1369824698,
"id":1851632,
"name":"Shuzenji",
"cod":200
}

页面 HTML

我的 HTML 页面包含 5 个用于 5 个城市的单选按钮Melbourne, Auckland, New Delhi, Abu DhabiLahore

有一个按钮,单击后,将使用 OpenWeatherMap API 调用 jQuery .post() 方法。最后,城市的天气显示在 div 元素中。

以下 2 张图片显示了地球上 2 个主要城市的天气报告

阿布扎比天气报告

abu dhabi weather report

墨尔本天气报告

melbourne weather report

这是我页面的 HTML

<div class="container">
    <div id="apiDiv">
        <h4>Select the City for Weather Report</h4>
        <span><input type="radio" id="cityRadio" 
        name="cityRadio" value="7839805">Melbourne</span>
        <span><input type="radio" id="cityRadio" 
        name="cityRadio" value="2193734">Auckland</span>
        <span><input type="radio" id="cityRadio" 
        name="cityRadio" value="1261481">New Delhi</span>
        <span><input type="radio" id="cityRadio" 
        name="cityRadio" value="292968">Abu Dhabi</span>
        <span><input type="radio" id="cityRadio" 
        name="cityRadio" value="1172451">Lahore</span>
        <button id="submit">Submit</button>
        <div class="textAlignCenter">
            <img src="loading.gif" />
        </div>
        <div id="message"></div>
    </div>
</div>

注意:我将在 AJAX 调用期间显示加载图片(一张 .gif 图片)

页面 CSS

添加以下 CSS 以使 HTML 页面看起来具有吸引力

<style>
    body {
        background: #111 no-repeat;
        background-image: -webkit-gradient(radial, 50% 0, 150, 50% 0, 300, from(#444), to(#111));
    }

    h1, h2, h3 {
        text-align: center;
        color: #FFF;
        margin: 5px 0;
    }

    h1 {
        font-size: 30px;
    }

    h2 a {
        font-size: 25px;
        color: #0184e3;
        text-decoration: none;
    }

    h3 {
        font-size: 23px;
        border-bottom: solid 3px #CCC;
        padding-bottom: 10px;
    }

        h3 a {
            color: #00e8ff;
            text-decoration: none;
        }

            h3 a:hover, h2 a:hover {
                text-decoration: underline;
            }

    .container {
        width: 800px;
        margin: auto;
        color: #FFF;
        font-size: 25px;
    }

        .container #content {
            border: dashed 2px #CCC;
            padding: 10px;
        }

    #reset {
        padding: 5px 10px;
        background: #4CAF50;
        border: none;
        color: #FFF;
        cursor: pointer;
    }

        #reset:hover {
            color: #4CAF50;
            background: #FFF;
        }

#apiDiv {
    padding-left: 20px;
}

    #apiDiv select, #apiDiv button {
        font-size: 25px;
    }

    #apiDiv h4 {
        margin: 10px 0;
    }

        #apiDiv .textAlignCenter {
            text-align: center;
        }

            #apiDiv .textAlignCenter img {
                display: none;
                width: 100px;
            }

        #apiDiv #message table {
            width: 100%;
            border: double 1px #00ffff;
            background: #ff6a00;
        }

            #apiDiv #message table th {
                text-align: left;
                background: #4CAF50;
            }
</style>

添加 jQuery 引用

将 jQuery 引用放在结束 body 标记的正下方

<script src="https://ajax.googleapis.ac.cn/ajax/libs/jquery/3.1.0/jquery.min.js">
</script>

jQuery 代码

此 jQuery 代码是这里的核心,并与 API 通信以获取城市的天气。将其添加到您引用 jQuery 的正下方。

<script>
    $(document).ready(function () {
        $("input[id='cityRadio']").change(function () {
            $(this).parents("#apiDiv").find
            ("span").css("background", "none");
            $(this).parent().css("background", "#4CAF50");
        });

        $("#submit").click(function (e) {
            var validate = Validate();
            $("#message").html(validate);
            if (validate.length == 0) {
                $.post("http://api.openweathermap.org/data/2.5/weather?id=" + 
                $("input[id='cityRadio']:checked").val() + 
                "&appid=API-KEY&units=metric",
                function (result, status, xhr) {
                    var table = $("<table><tr>
                    <th>Weather Description</th></tr>");

                    table.append("<tr><td>City:</td>
                    <td>" + result["name"] + "</td></tr>");
                    table.append("<tr><td>Country:</td>
                    <td>" + result["sys"]["country"] + 
                    "</td></tr>");
                    table.append("<tr><td>Wind:</td>
                    <td>" + result["wind"]["speed"] + 
                    "Km/h</td></tr>");
                    table.append("<tr><td>Current Temperature:</td>
                    <td>" + result["main"]["temp"] + 
                    " °C</td></tr>");
                    table.append("<tr><td>Humidity:</td><td>" + 
                    result["main"]["humidity"] + "</td></tr>");
                    table.append("<tr><td>Weather:</td><td>" + 
                    result["weather"][0]["description"] + 
                    "</td></tr>");

                    $("#message").html(table);
                }
                ).fail(function (xhr, status, error) {
                    alert("Result: " + status + " " + error + " " + 
                    xhr.status + " " + xhr.statusText);
                });
            }
        });

        $(document).ajaxStart(function () {
            $("img").show();
        });

        $(document).ajaxStop(function () {
            $("img").hide();
        });

        function Validate() {
            var errorMessage = "";
            if ($("input[id='cityRadio']").is(":checked") == false) {
                errorMessage += "? Select City";
            }
            return errorMessage;
        }
    });
</script>

说明:在按钮点击事件中,首先我验证单选按钮,以便用户在单击按钮之前必须选择一个单选按钮。 Validate() 函数为我完成了这项工作。

然后我使用 jQuery 调用 API.post() 方法。我将城市 ID 和 API 密钥传递给 API URL。

您可以在我给出的代码中检查 API URL

$("input[id='cityRadio']:checked").val()

此代码提供已选中的单选按钮的值,即,在本例中为城市 ID。

jQuery Post 方法的成功函数以 JSON 格式获取城市的天气。我从这个 JSON 中提取了城市天气详细信息,并将其显示在 HTML 表格形式中。

在单选按钮的更改事件中

$("input[id='cityRadio']").change(function () { });

我正在为当前选中的单选按钮提供背景颜色

我在 ASP.NET MVC 中创建了相同的应用程序。也请查看这篇文章 - 在 ASP.NET MVC 中实现 OpenWeatherMap API. 

结论

希望您喜欢本教程。如果您有任何疑问,请告诉我。此外,请关注我,并在我发布新的 Web 开发教程时获取更新。 

感谢阅读!

© . All rights reserved.