使用XHR的异步请求

时间:2018-05-22 07:55:38

标签: javascript ajax asynchronous xmlhttprequest httprequest

我需要编写异步请求以在搜索输入中查找相应的文章。 我使用的是Unplash.com和纽约时报的API。 代码不会在开发工具中显示任何错误。 我附上了codepen链接:

Codepen demo

(function(){
  const form = document.querySelector('#search-form');
  const searchField = document.querySelector('#search-keyword');
  let searchedForText;
  const responseContainer = document.querySelector('#response-container');

  form.addEventListener('submit', function(e) {
    e.preventDefault();
    responseContainer.innerHTML = '';

    function addArticles () {}

    function addImage() {}

   const imgRequest = new XMLHttpRequest();
   imgRequest.onload = addImage;
   imgRequest.onerror = function(err) {
     requestError(err, 'image');
   };
   imgRequest.open('GET', `https://api.unsplash.com/search/photos?page=1&query=${searchedForText}`);
   imgRequest.setRequestHeader('Authorization', 'Client-ID <27182>');
   imgRequest.send();

   const articleRequest = new XMLHttpRequest();
   articleRequest.onload = addArticles;
   articleRequest.onerror = function (err) {
     requestError(err, 'articles');
   }
   articleRequest.open('GET', 
   `http://api.nytimes.com/svc/search/v2/articlesearch.json? 
   q=${searchedForText}&api-key=<4c32dbc91636470fb8e286e60041dca5>`);
   articleRequest.send();

  });
});

0 个答案:

没有答案