我正在使用一个简单的web来获取伦敦金融城( city )的天气细节。但是,我没有得到所需的响应,而是一个401错误。我做错什么了吗?
<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
误差

发布于 2016-07-12 08:59:58
您需要将键作为查询字符串添加到天气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
}
});
});
});https://stackoverflow.com/questions/38322949
复制相似问题