【问题标题】:Openweathermap API ASK not workingOpenweathermap API ASK 不起作用
【发布时间】:2018-03-04 18:38:09
【问题描述】:

您好,我正在尝试做简单的天气应用,但我无法从 API 获得请求。

有人可以帮我吗?

$(document).ready(function testCall(){
  $.ajax({
    url: `http://api.openweathermap.org/data/2.5/weather?`,
    dataType: `JSON`,
    id: `7531860`,
    APPID: `8d3beea42a62c24610f3d57a8082a9c0`,
    success: function(data) {
      console.log("lol")
    },
    error: function(){
      console.log("WHy?")
    }

  });
})

【问题讨论】:

  • 你得到什么错误?
  • 我被记录了“为什么?”,但我应该得到一个“大声笑”,因为我猜我的请求很好
  • 不要说“它不工作”,而是对什么不工作提供建设性的解释。提供一个 fiddle 或 plunker,以便成员可以使用您的代码并为您提供帮助。
  • 我是初学者,对不起

标签: javascript api openweathermap


【解决方案1】:

好的,首先,错误回调函数接收参数,您可以使用它来了解发生了什么。使用您的代码,稍作修改,我得到的状态代码为 0。

error: function(xhr, exception){
  console.log("WHy?")
  console.log(xhr.status);
  console.log(exception);
}

我对使用 jQuery 的 ajax 不太熟悉,所以如果你想使用 jQuery,也许有人可以帮助你。下面我提供了一种方法来使用内置的 Fetch API 完成你想要的。这是Fiddle

function getWeatherData(Id, appId) {
    return fetch(`https://api.openweathermap.org/data/2.5/weather?id=${Id}&APPID=${appId}`)
    .then(res => res.json())
}

const YOUR_ID = null; // Replace Me
const YOUR_APP_ID = null; // Replace Me

getWeatherData(YOUR_ID, YOUR_APP_ID)
.then(weatherData => {
   // Work with your data
   console.log(weatherData);
});

包含您的 API 信息有助于解决此问题,但您现在应该重置它!

编辑:在使用 fetch 重写时,我发现了问题所在。该状态代码是由 url 中的拼写错误引起的。您需要通过 https 请求,而不是 http。您还需要将查询参数添加到请求中,而不是对象上。见下文和fiddle

$(document).ready(function testCall(){
  $.ajax({
    url: `https://api.openweathermap.org/data/2.5/weather?id=PUT_YOUR_ID_HERE&APPID=PUT_YOUR_APP_ID_HERE`,
    dataType: `JSON`,
    success: function(data) {
    console.log(data);
    },
    error: function(xhr, exception){
    console.log("WHy?")
    console.log(xhr);
    console.log(xhr.status);
    console.log(exception);
    }
  });
});

【讨论】:

    猜你喜欢
    • 2015-12-25
    • 1970-01-01
    • 2017-12-15
    • 2020-07-09
    • 1970-01-01
    • 2020-06-24
    • 1970-01-01
    • 2020-03-04
    • 1970-01-01
    相关资源
    最近更新 更多