使用 Javascript 从 openweathermap API 检索 5 天天气海报

Retrieving 5 day weather poster from openweathermap API Using Javascript

我收到 404 错误。我只想使用 openwheathermap api 检索 5 天的天气信息(严格来说 javascript,没有 jquery。我正在练习 api 和 javascript 并且相同的结构适用于一部电影 api。我犯了什么错误。下面是我目前的代码

ps: 预览时缩小到 25%

function enterkey(){
 
 var enterk = event.which || event.keyCode;
 
 if(enterk==13){
  
  showheather();
 }
 
}

function showheather(){
 
 
 
 var cName = document.getElementById("searchbox").value;
 var wgoes = document.getElementById("posterdiv");
 var urlapi = "api.openweathermap.org/data/2.5/weather?q="+cName+"";
 
 
 var http = new XMLHttpRequest();
 
 http.open("GET",urlapi,true)
 http.send()
 
 
  http.onreadystatechange = function(){
        
        if(http.status==200 && http.readyState==4){
            
            var wdata =JSON.parse(http.responseText)
   
   
   
   wgoes.innerHTML = wdata.city.name
   
   
   
  }
  
  
  
  
  
 }
 
 
}
#wraper{
margin: 0 auto;
height: 4000px;
width:3840px;

}
#posterdiv{
margin-top: 0%;
height: 2345px;
width:3840px;
border: 5px solid blue;
border-radius: 15px;
}

#searchbox{
height: 300px;
width:3840px;
font-size: 250px;
letter-spacing: 50px;
border-style: none;
 
}
<!DOCTYPE html>
<html>
<head>
 <link rel="stylesheet" type="text/css" href="../css/weather.css">
 
  <title></title>
</head>
<body>
  
<div id="wraper">
 
 
 <input type="text" id="searchbox" placeholder="Type City Name Here.." onkeydown="enterkey()" >
 
 <div id="posterdiv"></div>
 
 
 
 
 
 
</div> 
 
 
 
 
 
<script src = "../JavaScript/weather.js"></script>
 
</body>
</html>

需要通过urlapi

传入完整的绝对路径

现在它是一个相对路径,因此您要将 API 调用发送到您自己的主机。

opeanweathermap 还需要一个 API 密钥,您需要在 url.

中传递该密钥

function enterkey(){
 
 var enterk = event.which || event.keyCode;
 
 if(enterk==13){
  
  showheather();
 }
 
}

function showheather(){
 
 
 
 var cName = document.getElementById("searchbox").value;
 var wgoes = document.getElementById("posterdiv");
 var urlapi = "http://api.openweathermap.org/data/2.5/weather?q="+cName+"&appid='enter your app id'";
 
 
 var http = new XMLHttpRequest();
 
 http.open("GET",urlapi,true)
 http.send()
 
 
  http.onreadystatechange = function(){
        
        if(http.status==200 && http.readyState==4){
            
            var wdata =JSON.parse(http.responseText)
   
   
   
   wgoes.innerHTML = wdata.city.name
   
   
   
  }
  
  
  
  
  
 }
 
 
}

api 关键是问题所在。 openweathermap 要求用户拥有 api 密钥。不只是 json link。还添加 http .works like a charm now