带Ajax的天气网站使用开放天气地图API不会返回数据 [英] Weather Website With Ajax Using Open Weather Map API Not Returning Data

查看:71
本文介绍了带Ajax的天气网站使用开放天气地图API不会返回数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想建立一个网站,如果输入城市名称,我可以看到温度.这是我的代码,但是由于某种原因它无法正常工作!请帮忙!

I want to build a website where if I enter a city name I can see the temperature. This is my code but for some reason it is not working! Please help!

首先,我将显示JavaScript代码,然后将显示HTML代码.

First I will show the JavaScript code and then I will show te HTML code.

$(document).ready(function(){
    $('#submitWeather').click(function(){
        var city = $("#city").val();
        if (city != ''){
            $.ajax({
                url: 'https://api.openweathermap.org/data/2.5/weather?q=' + city + "&units=metric" + "&APPID=xxx",
                type: "GET",
                dataType: "jsonp",
                success: function(data){
                    var widget = show(data);
                    $("#show").html(widget);
                    $("#city").val('');
                }
            });
        }else{
            $("#error").html('Field cannot be empty');
        }
    });
});
function show(data) {
    return "<h3><strong>Weather</strong>: "+ data.main[0].temp +"</h3>"
}

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>

<div class="row">
    <h3 class="text-center text-primary">Enter City Name</h3>
    <span id="error"></span>
</div>
<div class="row form-group form-inline" id="rowDiv">
    <input type="text" name="city" class="form-control" placeholder="City Name">
    <button id="submitWeather" class="btn btn-primary">Search City</button>
</div>
<div id="show"></div>

有人知道我做错了吗?请告诉我!我使用此视频创建了网站: https://www.youtube.com/watch?v= 6imiFFeDIzE

Does anyone know what I did wrong? Please let me know! I used this video to create the website: https://www.youtube.com/watch?v=6imiFFeDIzE

推荐答案

在您的show函数中,它尝试获取 data.main [0] .temp .Open Weather Map API并未将主字段指定为数组,而只是一个对象.因此,请删除 [0] 部分,因为它不是数组,而只是对象.
您还需要将密钥放入代码中,因此您可能需要重置它.
另外,您尝试选择名称为 city 的输入框,但实际上是在选择ID为 city 的输入框,该输入框不存在.在输入元素上添加一个名为 id 的属性,其值为 city .

In your show function, it tries to get data.main[0].temp. The Open Weather Map API doesn't specify the main field as an array, it's just an object. So remove the [0] part because it's not an array and just an object.
You also put your key in the code, so you might want to reset it.
Also, you try to select the input box with the name of city but you actually are selecting the input box with the ID of city, which doesn't exist. On the input element add an attribute named id with the value being city.

这篇关于带Ajax的天气网站使用开放天气地图API不会返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆