2017-02-22 215 views
0

我從openweathermap.org得到錯誤信息。 它正在返回網站上給出的示例中顯示的信息。OpenWeatherMap返回錯誤結果

這裏是我的HTML代碼:

<!DOCTYPE html> 
<html> 
    <head> 
    <title>Your Weather</title> 
     <meta charset="utf-8"> 
     <link rel="stylesheet" href=""> 
    </head> 
    <body> 
     <div> 
     <h1>The Weather</h1> 
      <div> 
       <p> 
        <span id="show-weather"></span> 
        <span id="show-country"></span> 
       </p> 
      </div> 
     </div> 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
     <script src="custom.js"></script> 
    </body> 
</html> 

這是我的JS代碼:

$(document).ready(function() { 
    $.ajax({ 
     type: 'GET', 
     data: { 
      id: '2172797', 
      appid: 'b1b15e88fa797225412429c1c50c122a1' 
     }, 
     url: 'https://openweathermap.org/data/2.5/weather/', 
     xhrFields: { 
      withCredentials: false 
     }, 
     headers: {}, 
     success: function(data) { 

      $("#show-weather").text("Your location latitude is: " + data.coord.lat + " and longitude is: " + data.coord.lon); 
      $("#show-country").text(" Your current location is: " + data.sys.name); 

     }, 
     error: function(data) { 

      console.log('error'); 
      console.log(data); 
     }, 
    }); 
}); 

我無法得到像城市名稱或緯度或經度的當前信息。

+0

響應是什麼樣的?你的控制檯是否出現錯誤? – zero298

回答

0

name屬性位於根級別,因此您需要使用data.name屬性,如果您需要國家/地區名稱,則值應爲data.sys.country。沒有名爲name屬性下data.sys

完整的工作代碼:

$(document).ready(function() { 
 
    $.ajax({ 
 
     type: 'GET', 
 
     data: { 
 
      id: '2172797', 
 
      appid: 'b1b15e88fa797225412429c1c50c122a1' 
 
     }, 
 
     url: 'https://openweathermap.org/data/2.5/weather/', 
 
     xhrFields: { 
 
      withCredentials: false 
 
     }, 
 
     headers: {}, 
 
     success: function(data) { 
 
//console.log(data); 
 
      $("#show-weather").text("Your location latitude is: " + data.coord.lat + " and longitude is: " + data.coord.lon); 
 
      $("#show-country").text(" Your current location is: " + data.sys.country); 
 

 
     }, 
 
     error: function(data) { 
 

 
      console.log('error'); 
 
      console.log(data); 
 
     }, 
 
    }); 
 
});
<body> 
 
     <div> 
 
     <h1>The Weather</h1> 
 
      <div> 
 
       <p> 
 
        <span id="show-weather"></span> 
 
        <span id="show-country"></span> 
 
       </p> 
 
      </div> 
 
     </div> 
 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
 
     
 
    </body>

0

你與請求發送ID查詢參數是一個城市的ID ...相同id在文檔中使用的示例。更改ID或查看關於如何使用其他查詢參數查詢其他城市的文檔。