Spinner для REST API с использованием чистого JS - PullRequest
0 голосов
/ 31 августа 2018

Я вызываю rest API и пытаюсь использовать spinner перед загрузкой результата.

Он написан на чистом JS, поэтому я не могу найти правильное решение для него.

Вот мой код. Мне нужен предварительный загрузчик для загрузки, пока не отобразится результат. например, до no result found я хочу немного блесны. Я закодировал спиннер, но мне нужно отображать его, пока скрипт не запустится. у меня может работать console.log, там я могу заменить скрипт spinner.

Спасибо

function callREST() {
  const app = document.getElementById('root');

  while (app.firstChild) {
    app.removeChild(app.firstChild);
  }

  var inputForm = document.getElementById('zip');
  var code = inputForm.value;

  var request = new XMLHttpRequest();
  request.open('GET', 'Path to API URL' + code, true);

  request.onload = function() {

    // Begin accessing JSON data here
    var responseData = JSON.parse(this.response);
    var data = responseData.Agents.Agent;

    if (request.status >= 200 && request.status < 400) {

      var zip = responseData.Agents['@ZipCode'];

      if (typeof data == 'undefined' || zip != code) {
        const noData = document.createElement('div');
        noData.setAttribute('class', 'container text-center font-weight-bold pt-3');
        noData.textContent = 'No agent available.';
        app.appendChild(noData);
      } else if (zip === code) {

        for (var i = 0; i < data.length; i++) {
          var agent = data[i];

          const card = document.createElement('div');
          card.setAttribute('class', 'result');

        };
      }

    } else {
      const errorMessage = document.createElement('div');
      errorMessage.textContent = "Something is not right!";
      app.appendChild(errorMessage);
    }
  }


  request.send();
}
<div id="wrapper">
  <main id="main">
    <form action="#" class="question-form">
      <h1>Enter your zip code</h1>
      <div class="form-group">
        <label for="zip">Zip Code</label>
        <input type="text" id="zip" class="form-control" oninput="zipData()">
      </div>
      <div class="button-holder">
        <button class="btn btn-primary" onclick="callREST()">Search</button>
      </div>
    </form>
    <div id="root"></div>
  </main>
  <div id="loader" class="loading-overlay">
    <img src="images/spinner.svg" alt="image description">
  </div>
</div>

1 Ответ

0 голосов
/ 31 августа 2018

Итак, три вещи:

  1. Установите предварительный загрузчик на display:none с самого начала. Я установил это здесь.
  2. Установите предварительный загрузчик на diplay: block при выполнении callREST(). Сделайте это первым делом после объявления переменных.
  3. Установите предварительный загрузчик обратно на display:none после request.readyState === 4 (и / или любого другого условия, которое вы хотите проверить)

Вот и мы:

function callREST() {
  const app = document.getElementById('root'),
        preloader = document.getElementById('loader');

  preloader.setAttribute('style', 'display:block');

  while (app.firstChild) {
    app.removeChild(app.firstChild);
  }

  var inputForm = document.getElementById('zip');
  var code = inputForm.value;

  var request = new XMLHttpRequest();
  request.open('GET', 'Path to API URL' + code, true);

  request.onload = function() {

    // Begin accessing JSON data here
    var responseData = JSON.parse(this.response);
    var data = responseData.Agents.Agent;

    if (request.status >= 200 && request.status < 400) {

      var zip = responseData.Agents['@ZipCode'];

      if (typeof data == 'undefined' || zip != code) {
        const noData = document.createElement('div');
        noData.setAttribute('class', 'container text-center font-weight-bold pt-3');
        noData.textContent = 'No agent available.';
        app.appendChild(noData);
      } else if (zip === code) {

        for (var i = 0; i < data.length; i++) {
          var agent = data[i];

          const card = document.createElement('div');
          card.setAttribute('class', 'result');

        };
      }

    } else {
      const errorMessage = document.createElement('div');
      errorMessage.textContent = "Something is not right!";
      app.appendChild(errorMessage);
    }
  }


  request.send();

  request.onreadystatechange = function() {

      if (request.readyState === 4) {
          preloader.setAttribute('style', 'display:none');
      }
  }
}
<div id="wrapper">
  <main id="main">
    <form action="#" class="question-form">
      <h1>Enter your zip code</h1>
      <div class="form-group">
        <label for="zip">Zip Code</label>
        <input type="text" id="zip" class="form-control" oninput="zipData()">
      </div>
      <div class="button-holder">
        <button class="btn btn-primary" onclick="callREST()">Search</button>
      </div>
    </form>
    <div id="root"></div>
  </main>
  <div id="loader" class="loading-overlay" style="display:none;">
    <img src="images/spinner.svg" alt="image description">
  </div>
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...