【问题标题】:Not able to get data from openweatherapi无法从 openweathermap 获取数据
【发布时间】:2018-05-17 01:39:00
【问题描述】:

我正在尝试创建一个简单的天气应用程序,并且我正在使用 jquery Ajax 方法从 openweathermap 检索数据。我正在使用以下方法获取数据。

$(document).ready(function(){
$('#submitWeather').click(function(){
let city = $("#city").val();
if(city != ''){
  //Get the AJAX request.
  $.ajax({
    url:'http://api.openweathermap.org/data/2.5/weather?q=' + city + "&appid=b1b15e88fa797225412429c1c50c122a1",
    type: "GET",
    //jsonpadded.
    dataType: "jsonp",
    //the callback for success.
    success: function(data){
      console.log(data);
    }
  });
}else {
  $("#error").html('Field cannot be empty');
}
 });
 });

我遇到的问题是它没有获得在 console.log 中显示的数据。这是我在 console.log 中遇到的错误

jquery.min.js:4 GET http://api.openweathermap.org/data/2.5/weather?q=London&appid=b1b15e88fa797225412429c1c50c122a1&callback=jQuery31106677768465103353_1512307813960&_=1512307813961 net::ERR_ABORTED
send @ jquery.min.js:4
ajax @ jquery.min.js:4
(anonymous) @ app.js:6
dispatch @ jquery.min.js:3
q.handle @ jquery.min.js:3

【问题讨论】:

  • 只要将该 URL 放在浏览器中就表明 API 正在返回“401 Invalid API Key Response”。您应该确保您使用的是有效的初学者 API 密钥。
  • 我是个笨蛋。我用错了钥匙。谢谢罗伯特;)
  • 我以为他没有把自己的APPID公之于众,只是一个占位符appid,用于演示目的。

标签: jquery ajax api openweathermap


【解决方案1】:

ajax请求的dataType是“json”而不是“jsonp”

dataType(默认:Intelligent Guess(xml、json、script 或 html))

参考:http://api.jquery.com/jquery.ajax/

$.ajax({
    url:'http://api.openweathermap.org/data/2.5/weather?q=' + city + "&appid=b1b15e88fa797225412429c1c50c122a1",
    type: "GET",
    dataType: "json",
    success: function(data){
      console.log(data);
    }
  });

更新:

openweathermap 支持“JSONP”,但你用错了这里是一个如何使用 $.ajax 来调用命名方法的例子

function callback(data){
    console.log(data);
}

$.ajax({
    url:'http://api.openweathermap.org/data/2.5/weather?q=' + city + "&appid=b1b15e88fa797225412429c1c50c122a1",
    type: "GET",
    dataType: "jsonp",
        jsonp : "callback",
        jsonpCallback: "callback"
        });

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2018-08-22
  • 2020-02-03
  • 1970-01-01
  • 2015-10-06
  • 1970-01-01
  • 2021-12-31
  • 1970-01-01
  • 2016-06-15
相关资源
最近更新 更多