当前位置:首页 > 开发教程 > ajax教程 >

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

时间:2019-03-04 21:56 来源:互联网 作者:源码搜藏 收藏

介绍 使用 jQuery Post 方法,您可以轻松地调用任何 API 和Web服务。 在本教程中,我将教您如何使用此方法进行API调用。 我选择了 OpenWeatherMap API来向您说明代码。 要告诉你更多关于 OpenWeatherMapAPI - 这是一个非常受欢迎和免费的天气API,它提供了地

介绍

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

我选择了OpenWeatherMapAPI来向您说明代码。要告诉你更多关于OpenWeatherMapAPI这是一个非常受欢迎和免费的天气API,它提供了地球上所有城市的天气信息。

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

背景

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

OpenWeatherMap API URL

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

http://api.openweathermap.org/data/2.5/weatherid=CITYIDappid=APIKEY&units=metric

在这里,我们传递CITYIDAPIKEY到达此URL。

OpenWeatherMap JSON

API以JSON格式返回响应此JSON包含城市的天气信息。OpenWeatherMapJSON的样子:

{
"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

MYHTML页面包含5个城市5个单选按钮 - ,MelbourneAuckland New DelhiAbu DhabiLahore

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

以下2幅图像显示了这个星球上2个主要城市的天气预报:

阿布扎比天气报告

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

墨尔本天气报告

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

这是我的页面的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.com/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/weatherid=" + 
                $("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 .post() 方法调用API我将城市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开发教程时,请关注我并获得更新。 

谢谢你的阅读!


ajax教程阅读排行

最新文章