Flickr API总是返回相同的数据

时间:2019-01-17 13:50:20

标签: javascript jquery ajax api

我有一个小型天气应用。我通过“ POST”请求获取天气数据,并将其附加到文档中,效果很好。

用户可以按城市查询天气,现在我想使用单独的jQuery $ Ajax()请求加载该城市的图像。

但是,我总是得到相同的结果。

与应用相关的应用结构如下:

 <input id="getIt" name="cityajax" type="text" class="ghost-input" 
 placeholder="Enter a City" required> // get user input, querying a city
 <button id="submit">Submit</button>

         <span class="humidLogo">Current humidity:</span> <i class="fas fa-temperature-low" ></i>    <span class="apiHumidity"> % </span>


       <div class="FlickResponse"></div> // flickrResposnse gets appended here
   </div>

CSS不相关,因此我立即跟进了相关的JS函数:

var destination = $("#getIt").val(); // cache the user input, I am not sure I have to listen for a change event here and then update the state.
var flickerAPI =
  "https://api.flickr.com/services/feeds/photos_public.gne?format=json&tags=" +
  destination; // the url to get access the api

$.ajax({
  url: flickerAPI,
  dataType: "jsonp", // jsonp
  jsonpCallback: "jsonFlickrFeed", // add this property
  success: function(result, status, xhr) {
    $(".FlickResponse").html(""); // here I want to empty the contents of the target div, but this never happens
    $.each(result.items, function(i, item) {
      $("<img>")
        .attr("src", item.media.m)
        .addClass("oneSizeFitsAll")
        .appendTo(".FlickResponse");
      if (i === 1) {
        return false;
      }
    });
  },
  error: function(xhr, status, error) {
    console.log(xhr);
    $(".FlickResponse").html(
      "Result: " +
        status +
        " " +
        error +
        " " +
        xhr.status +
        " " +
        xhr.statusText
    );
  }
});

仅此而已。那么,为什么我总是从API得到相同的响应?我是否必须在输入字段上收听更改事件?因为POSt请求可以在没有更改事件侦听器的情况下工作。

是因为我正在查询2个API,并且我使用了相同的输入字段作为值(愚蠢的问题,但您永远不知道x)。

这是一个带有完整代码的Codepen,只需输入城市并单击提交按钮即可:

https://codepen.io/damPop/pen/qLgRvp?editors=1010

1 个答案:

答案 0 :(得分:1)

我会将图像检索(和天气查询)拉入另一个功能,如下所示,那么您很好!

我已经分叉到另一个codepen:updated example

function loadDestinationImage() {
    var destination = ($("#getIt").val());
    var flickerAPI = "https://api.flickr.com/services/feeds/photos_public.gne?format=json&tags=" +  destination;
    $.ajax({
        url: flickerAPI,
        dataType: "jsonp", // jsonp
        jsonpCallback: 'jsonFlickrFeed', // add this property
        success: function (result, status, xhr) {
            $(".FlickResponse").html("");
            $.each(result.items, function (i, item) {
                $("<img>").attr("src", item.media.m).addClass("oneSizeFitsAll").appendTo(".FlickResponse");
                if (i === 1) {
                    return false;
                }
            });
        },
        error: function (xhr, status, error) {
                console.log(xhr)
                $(".FlickResponse").html("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
        }
    });
}

我也会对天气做同样的事情

 function loadWeather() {
    var destination = ($("#getIt").val());

    $.post("https://api.openweathermap.org/data/2.5/weather?q=" +
    destination +
    "&units=metric&appid=15c9456e587b8b790a9092494bdec5ff",
    function (result, status, xhr) {

        var APIresponded =  result["main"]["temp"];
        var APIweather =  result["weather"][0]["description"];
        var sunGoing = result["sys"]["sunset"];
        var output = destination.capitalize();
        var humidValue = result["main"]["humidity"];
        var windy = result["wind"]["speed"];
        var windDirection = result["wind"]["deg"];

        if (windDirection <= 90) {
          windDirection = "southwest"
        }
        if (windDirection <= 180) {
          windDirection = "northwest"
        }
        if (windDirection <= 270) {
          windDirection = "northeast"
        }
        if (windDirection <= 360) {
          windDirection = "southeast"
        }
        if (APIweather.includes("snow")) {
          $('#displaySky').addClass('far fa-snowflake');
        }
        if (APIweather.includes("rain")) {
          $('#displaySky').addClass('fas fa-cloud-rain');
        }
        if (APIweather.includes("overcast")) {
          $('#displaySky').addClass('fas fa-smog');
        }
        if (APIweather.includes("sun") || APIweather.includes("clear")) {
          $('#displaySky').addClass('fas fa-sun');
        }
        if (APIweather.includes("scattered")) {
          $('#displaySky').addClass('fas fa-cloud-sun');
        }
        $("#message").html("The temperature in " + output + " is : " + APIresponded + " degrees. The sky looks like this: ");
        $(".apiHumidity").text(humidValue + " %");

        $('.apiWind').html(windy + 'km per hour. The wind direction is  ' + windDirection);
        console.log(APIweather);
    }

    ).fail(function (xhr, status, error) {
        alert("Result: " + status + " " + error + " " +
        xhr.status + " " + xhr.statusText);
    });
}

然后从Submit函数调用:

$("#submit").click(function (e) {   
    loadDestinationImage();
    loadWeather();
});