简体   繁体   English

Openweathermap API ASK不起作用

[英]Openweathermap API ASK not working

Hello im trying to do simple weather app but i cant get a request from API. 你好,我试图做一个简单的天气应用程序,但我无法从API获得请求。

Somone can help me? 有人可以帮我吗?

$(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?")
    }

  });
})

Okay, first thing, the error callback function receives arguments you can use to learn a about what occurred. 好的,第一件事,错误回调函数接收可用于了解发生情况的参数。 Using your code, slightly modified, I was getting a status code of 0. 使用您的代码(稍作修改),我得到的状态代码为0。

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

I am not too familiar with using jQuery's ajax, so maybe someone can help you with that if you wish to use jQuery. 我对使用jQuery的ajax不太熟悉,所以如果您想使用jQuery,也许有人可以帮助您。 Below I have provided a way to accomplish what you want using the built in Fetch API. 下面,我提供了一种使用内置的Fetch API完成所需功能的方法。 Here is the 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);
});

Including your API information was helpful for solving this, but you should now reset it! 包括您的API信息有助于解决此问题,但是您现在应该将其重置!

EDIT : in rewriting with fetch, I figured out what was wrong. 编辑 :在用fetch重写时,我发现了什么地方出了问题。 That status code was caused by a typo in the url. 该状态代码是由网址中的错字引起的。 You need to request over https, not http. 您需要通过https而不是http请求。 You also need to add the query params into the request, not on the object. 您还需要将查询参数添加到请求中,而不是对象上。 See below and the 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);
    }
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM