使用仅JavaScript的用户输入查询基于JSON的API

时间:2018-08-08 00:36:07

标签: javascript json api addeventlistener

我一直在观看有关使用JSON数据和JS的教程,决定使用API​​并制作一个简单的APP。我遇到了障碍,我不确定是什么引起了问题。问题出在我使用用户输入修改查询字符串的方式周围。当我将端点设为静态并摆脱“ movieSearch”功能时,就像这样:

const movies = [];
const endpoint = 'http://www.omdbapi.com/?apikey=myAPIkey=batman';

fetch(endpoint)
 .then(blob => blob.json())
 .then(data => movies.push(...data.Search));

只要它是静态的,它就可以按需工作。

我当前的代码是:

  const movies = [];

  function movieSearch() {
    const replace = this.value;
    const endpoint = 'http://www.omdbapi.com/?apikey=myAPIkey=' + replace;

    movies.length = 0;

    fetch(endpoint)
      .then(blob => blob.json())
      .then(data => movies.push(...data.Search));
  }

  function findMatches(wordToMatch, movies) {
    return movies.filter(film => {
      const regex = new RegExp(wordToMatch, 'gi');
      return film.Title.match(regex) || film.Year.match(regex)
    })
  }

  function displayMatches() {
    const matchArray = findMatches(this.value, movies);
    const html = matchArray.map(film => {
      const regex = new RegExp(this.value, 'gi');
      const titleName = film.Title.replace(regex, `<span class="hl">${this.value}</span>`)
      const yearName = film.Year.replace(regex, `<span class="hl">${this.value}</span>`)
      return `
        <li>
          <span class="name">${titleName}, ${yearName}</span>
          <span class="population">${film.imdbID}</span>
        </li>
      `;
    }).join('');
    suggestions.innerHTML = html;
  }

  const searchInput = document.querySelector('.search');
  const suggestions = document.querySelector('.suggestions');

  searchInput.addEventListener('keyup', displayMatches);
  searchInput.addEventListener('change', displayMatches);
  searchInput.addEventListener('keyup', movieSearch);

displayMatches函数开始表现有趣,有时返回列表项,而其他时候则不然。我不知道是什么原因造成的。无论我以哪种方式称呼端点,我的电影数组都看起来相同,所以我感到非常困惑。

有什么建议吗?有更好的方法吗?

我的HTML现在非常简单:

<form class="search-form">
 <input type="text" class="search" placeholder="Movies">
 <ul class="suggestions">
  <li>test1</li>
  <li>test2</li>
 </ul>
</form>

谢谢! (我正在尝试用JS完成所有操作)

编辑:

使用API​​搜索蝙蝠侠时的JSON数据示例:

{"Search":[{"Title":"Batman Begins","Year":"2005","imdbID":"tt0372784","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BZmUwNGU2ZmItMmRiNC00MjhlLTg5YWUtODMyNzkxODYzMmZlXkEyXkFqcGdeQXVyNTIzOTk5ODM@._V1_SX300.jpg"},{"Title":"Batman v Superman: Dawn of Justice","Year":"2016","imdbID":"tt2975590","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BYThjYzcyYzItNTVjNy00NDk0LTgwMWQtYjMwNmNlNWJhMzMyXkEyXkFqcGdeQXVyMTQxNzMzNDI@._V1_SX300.jpg"},{"Title":"Batman","Year":"1989","imdbID":"tt0096895","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BMTYwNjAyODIyMF5BMl5BanBnXkFtZTYwNDMwMDk2._V1_SX300.jpg"},{"Title":"Batman Returns","Year":"1992","imdbID":"tt0103776","Type":"movie","Poster":"https://ia.media-imdb.com/images/M/MV5BOGZmYzVkMmItM2NiOS00MDI3LWI4ZWQtMTg0YWZkODRkMmViXkEyXkFqcGdeQXVyODY0NzcxNw@@._V1_SX300.jpg"},{"Title":"Batman Forever","Year":"1995","imdbID":"tt0112462","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BNWY3M2I0YzItNzA1ZS00MzE3LThlYTEtMTg2YjNiOTYzODQ1XkEyXkFqcGdeQXVyMTQxNzMzNDI@._V1_SX300.jpg"},{"Title":"Batman & Robin","Year":"1997","imdbID":"tt0118688","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BMGQ5YTM1NmMtYmIxYy00N2VmLWJhZTYtN2EwYTY3MWFhOTczXkEyXkFqcGdeQXVyNTA2NTI0MTY@._V1_SX300.jpg"},{"Title":"The Lego Batman Movie","Year":"2017","imdbID":"tt4116284","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BMTcyNTEyOTY0M15BMl5BanBnXkFtZTgwOTAyNzU3MDI@._V1_SX300.jpg"},{"Title":"Batman: The Animated Series","Year":"1992–1995","imdbID":"tt0103359","Type":"series","Poster":"https://m.media-amazon.com/images/M/MV5BNzI5OWU0MjYtMmMwZi00YTRiLTljMDAtODQ0ZGYxMDljN2E0XkEyXkFqcGdeQXVyNTA4NzY1MzY@._V1_SX300.jpg"},{"Title":"Batman: Under the Red Hood","Year":"2010","imdbID":"tt1569923","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BYTdlODI0YTYtNjk5ZS00YzZjLTllZjktYmYzNWM4NmI5MmMxXkEyXkFqcGdeQXVyNTA4NzY1MzY@._V1_SX300.jpg"},{"Title":"Batman: The Dark Knight Returns, Part 1","Year":"2012","imdbID":"tt2313197","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BMzIxMDkxNDM2M15BMl5BanBnXkFtZTcwMDA5ODY1OQ@@._V1_SX300.jpg"}],"totalResults":"344","Response":"True"}

1 个答案:

答案 0 :(得分:1)

导致此行为的问题:

  1. faceView.addGestureRecognizer(UIPinchGestureRecognizer(target: faceView, action: #selector(changeScale(_:)))) 函数是异步的,可能无法及时更新数据。
  2. API有时会返回错误。

这通过下面的代码解决,请注意,我将所有内容都移到了fetch解析器中,以确保仅在API响应后才执行搜索。

这是一个JS Bin:https://jsbin.com/kicesivigu/1/edit?html,js,output

movieSearch