无法使用weather json API

时间:2017-05-11 11:41:38

标签: javascript json ajax api

我想从这个API获取天气详细信息,但由于一些奇怪的原因,它似乎无法正常工作。

它是一个mashape API。 https://market.mashape.com/fyhao/weather-13

这是我尝试过的,

function getWeather() {
  var lat=null;
  var lon=null;
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      lat = position.coords.latitude;
      lon = position.coords.longitude;
    });
  }
  var url =
    "http://simple-weather.p.mashape.com/weatherdata?lat=" +
     lat +
    "&lng=" +
    lon;
  $.ajax({
    url: url,
    type: "GET",
    dataType: "json",
    success: function(data) {
      $(".location").html(
        "<h4>" +
          data.query.results.channel.location.city +
          ", " +
          data.query.results.channel.location.country +
          "</h4>"
      );
      $(".weather").html(
        "<h4>" + data.query.results.channel.item.condition.text + "</h4>"
      );
      $(".temperature").html(
        "<h4>" + data.query.results.channel.item.condition.temp + "</h4>"
      );
    },
    error: function(err) {
      alert(err);
    },
    beforeSend: function(xhr) {
      xhr.setRequestHeader(
        "X-Mashape-Authorization",
        "MYKEY"
      );
    }
  });
}
$(document).ready(function() {
  $(".info").addClass("animated pulse");
  getWeather();
});

任何帮助将不胜感激。

编辑: - 我收到一个警告错误,上面写着&#34; [object Object]&#34;由于ajax中的错误功能。我最初没有看到错误,因为我阻止了页面上的弹出窗口。

1 个答案:

答案 0 :(得分:4)

一些事情:

  • getCurrentPosition()是异步的。在设置它的方式中,当lat和lon变量设置为坐标时,$ .ajax请求已经与null lat和lon变量一起发送
  • 此API需要https而不是http
  • 标题为X-Mashape-Key,而非X-Mashape-Authorization

以下是一个例子:

function getWeather() {
    var lat = null;
    var lon = null;
    if (navigator.geolocation) {
        //we are putting everything inside the callback
        navigator.geolocation.getCurrentPosition(function (position) {
            lat = position.coords.latitude;
            lon = position.coords.longitude;

            var url =
                "https://simple-weather.p.mashape.com/weatherdata?lat=" +
                lat +
                "&lng=" +
                lon;
            $.ajax({
                url: url,
                type: "GET",
                success: function (data) {
                    console.log(data);
                },
                error: function (err) {
                    console.error('error ' + JSON.stringify(err));
                },
                beforeSend: function (xhr) {
                    xhr.setRequestHeader(
                        "X-Mashape-Key", "KEY"
                    );
                }
            });

        });
    }
}
$(document).ready(function () {

    getWeather();
});