首页 > 解决方案 > 如何使用 JQuery 从 API 返回多个图像?

问题描述

我在这里做错了什么?我试图让用户选择 1-50 张图片,如果我请求超过 15 张图片但在控制台中显示“成功”,它会捕获错误。一旦它捕捉到超过 15 张图像的错误,我就无法提交以显示甚至少于 15 张图像。我是否需要在 displayResults 函数或 watchForm 函数下方更改某些内容,其中我有```const numInput = $("#num-dog").val();?


function displayResults(responseJson) {
  console.log(responseJson);
  $(".results-img").empty();
  for (let i = 0; i < responseJson.message.length; i++) {
    $(".results-img").append(
      `<li><img src="${responseJson.message[i]}" class="results-img"></li>`
    );
    //display the results section
  }
  console.log(displayResults);
  $("#results").removeClass("hidden");
}

function getDogImages(numInput) {
  let newUrl = randomUrl + numInput;

  fetch(newUrl)
    .then((response) => response.json())
    .then((responseJson) => displayResults(responseJson))
    .catch((error) => alert("Something went wrong. Try again later."));
}

function watchForm() {
  $("form").submit((event) => {
    event.preventDefault();
    const numInput = $("#num-dog").val();
    getDogImages(numInput);
  });
}

$(function () {
  console.log("App loaded! Waiting for submit!");
  watchForm();
});
}```


Here is part of the HTML:

```<section id="container">
        <h1>Dog API APP</h1>
        <form id="dogform">
            <label for="number of random dog images to display">How many dogs would you like to see?</label>
            <input type="number" min="1" max="50" id="num-dog" value="" required>
            <input type="submit" id="submitButton" value="Submit!" >
        </form>
    </section>
    <section id="results" class="hidden">
        <h2>Here are your dogs!</h2>
        <ul class="results-img" alt="placeholder">
    </section>```

标签: jqueryjsonapi

解决方案


我很确定问题出在 API 而不是您的代码上。


推荐阅读