Weather API(RESTful)给出错误

时间:2016-07-12 07:50:53

标签: jquery web-services rest asp.net-web-api

我使用简单的网络API获取城市伦敦的天气详情。但是,我没有得到所需的响应,而是 401错误。我做错了吗?

HTML

<html> 
<head> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
<script>
$(document).ready(function(){
    $('button').click(function(){
        $.ajax({
            type: "get",
            url: "http://api.openweathermap.org/data/2.5/weather?q=London",
            dataType: "json",
            contentType: 'application/json',
            success: function(data) {
                    //What to do on success 
            }
        });
    });
});
</script> 
</head> 

<body>
    <button>Click Me</button>
</body> 

</html> 

使用以下API

http://openweathermap.org/current

错误

enter image description here

1 个答案:

答案 0 :(得分:2)

您需要将密钥作为查询字符串添加到weather api的URL中。

您可以添加一个小功能来执行此操作:

var url = 'http://api.openweathermap.org/data/2.5/forecast/city';
var keys = {
    id: 524901,
    APPID: 12345 // Put your key here
}; 

function makeUrl (url, queryStringObject) {
    var query = [];
    // Loops through each key
    for(var key in queryStringObject){
        query.push(encodeURIComponent(key) + '=' +
            encodeURIComponent(queryStringObject[key]));
    }
    // Returns the url with the keys appended
    return url + (query.length ? '?' + query.join('&') : '');
}

这将返回api所需格式的密钥:

http://api.openweathermap.org/data/2.5/forecast/city?id=524901&APPID=12345 

然后在你对api的调用中,你可以使用函数调用:

$(document).ready(function(){
    $('button').click(function(){
        $.ajax({
            type: "get",
            url: makeUrl(url, keys), // Gets the constructed url
            dataType: "json",
            contentType: 'application/json',
            success: function(data) {
                    //What to do on success 
            }
        });
    });
});