jQuery API fetch请求不起作用,控制台日志显示工作链接,链接有结果,我错过了什么?

x7yiwoj4  于 2023-08-04  发布在  jQuery
关注(0)|答案(1)|浏览(94)

我正在设置对啤酒厂API的请求。简单的代码,它看起来很好,我试图解决它。我不知道错误是什么。下面是js文件,它记录了一个工作链接,但没有fetch结果
这是到repl的链接,这应该使它更容易。

'use strict';

function getBreweries(state) {
  const url = `https://api.openbrewerydb.org/breweries/search?query=${state}`;
  console.log(url)
  fetch(url)
  .then(response => response.json())
  .then(responseJson => {
    displayResults(responseJson)
  }
    );
  
}

function displayResults(responseJson) {
  console.log(responseJson);
  for (let i=0; i< responseJson.length; i++){
    console.log(responseJson[i].name);
    $('#js-search-results').html(responseJson[i].name);
  }

}

function watchForm() {
$('form').submit(event =>{
  const stateRaw = $('#js-query').val();
  const stateArray = stateRaw.split(" ");
  const state = stateArray.join("_");
  console.log(state);
  getBreweries(state);
})
}

$(watchForm);

字符串
在这里,我们有html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <script
          src="https://code.jquery.com/jquery-3.2.1.min.js"
          integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
          crossorigin="anonymous"></script>
    <link href="index.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <h1>Find a brewery</h1>
    <form action="#" id="js-search-form">
      <label for="state-entry">Search by state:</label>
      <input type="text" id="js-query" placeholder="New York">
      <input type="submit" value="Search"></input>
    </form>
    <section id="js-search-results">
            
    </section>
    <script src="index.js"></script>
  </body>
</html>

i34xakig

i34xakig1#

有几件事。
1.您需要在watchForm()中添加event.preventDefault(),以防止表单元素尝试其默认操作(向action属性中输入的路径发送请求)。
1.将$('#js-search-results').html();更改为$('#js-search-results').append();。否则你会在每次循环中覆盖之前的结果。
示例如下:

'use strict';

function getBreweries(state) {
  const url = `https://api.openbrewerydb.org/breweries/search?query=${state}`;
  console.log(url)
  fetch(url)
  .then(response => response.json())
  .then(responseJson => {
    displayResults(responseJson)
  }
    );
  
}

function displayResults(responseJson) {
  console.log(responseJson);
  $('#js-search-results').html("<ul></ul>")
  for (let i=0; i< responseJson.length; i++){
    console.log(responseJson[i].name);
    $('#js-search-results ul').append("<li>" + responseJson[i].name + "</li>");
  }

}

function watchForm() {
$('form').submit(event =>{
  event.preventDefault();
  const stateRaw = $('#js-query').val();
  const stateArray = stateRaw.split(" ");
  const state = stateArray.join("_");
  console.log(state);
  getBreweries(state);
})
}

$(watchForm);

个字符

相关问题