显示来自获取方法

时间:2017-09-28 17:55:30

标签: javascript html ajax api

我试图获取用户在搜索输入中输入的值, 然后我想将此变量传递到我的端点并返回数据

                <input type="text" class="search" placeholder="planet">



            <script>

            const media = 'image';

            const searchInput = document.querySelector('.search');
            searchInput.addEventListener('change', searchData);


            //get value of what is typed into search input.
            function searchData() {
                let search = this.value;
                const  finalData = getData(search);
            }


            // pass the search variable into the endpoint in getData function.
            function getData() {
            const endpoint = `https://images-api.nasa.gov/search?q=${search}&media_type=${media}`;
            console.log(endpoint);

            const  result = [];

            fetch(endpoint)
              .then(blob => blob.json())
              .then(data => result.push(...data.collection.items));
            }

我不确定我这样做是否正确,或者是否还有其他更好的方法,我还不熟悉JavaScript。谢谢。

1 个答案:

答案 0 :(得分:1)

你去吧

<input type="text" class="search" placeholder="planet">
<div class="output"></div>

<script>
  const media = 'image';
  const searchInput = document.querySelector('.search');
  const output = document.querySelector('.output')

  searchInput.addEventListener('change', searchData);

  //get value of what is typed into search input.
  async function searchData() {
    let search = this.value;
    const finalData = await getData(search);
    render(finalData);
  }

  function render(data) {
    output.innerHTML = JSON.stringify(data)
  }


  // pass the search variable into the endpoint in getData function.
  function getData(search) {
    const endpoint = `https://images-api.nasa.gov/search?q=${search}&media_type=${media}`;

    return fetch(endpoint)
      .then(blob => blob.json())
      .then(data => data.collection.items);
  }
</script>

在这里摆弄 https://jsfiddle.net/xyhk49wy/

您可以修改render函数,使其执行其他操作而不是显示字符串化的JSON