javascript - Flickr API 始终返回相同的数据

标签 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

最佳答案

我会将图像检索(和天气查找)放入另一个函数中,如下所示,那么就可以了!

我已经 fork 到另一个代码笔: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").click(function (e) {   
    loadDestinationImage();
    loadWeather();
});

关于javascript - Flickr API 始终返回相同的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54237393/

相关文章:

ajax - 如何在 Service Worker Fetch API 中检测 URL 请求是否为 ajax

asp.net - 如何使用 ASP.NET MVC 增加 AJAX JSON 响应的 2MB 限制

javascript - 从 ng-messages 中提取 ng-message key

javascript - 为什么当我将脚本加载到 div 中时此函数停止工作?

javascript - 切换可过滤的 div

javascript - AJAX 发布成功但 PHP 没有响应

javascript - 如何在本地保存使用 html2pdf 和 Node 生成的 pdf?

javascript - 为什么每次请求都会发送 cookie,但在浏览器控制台或 document.cookie 中看不到?

javascript - JS 从字符串中提取指数

jquery - Typeahead TypeError : it. toLowerCase 不是函数