在等待Ajax响应的同时显示加载程序,然后淡出加载程序并在响应中淡入,没有jQuery

时间:2018-11-04 13:13:57

标签: javascript

我使用的是常规XMLHttpRequest,我想在等待响应时显示加载元素,然后用动画显示响应。

我可以使用jQuery来做到这一点,但是我找不到香草JS的答案。

这是相关的代码。

<div id="loader"></div>
<div id="demo" class="animate-bottom">
ooo
</div>

<button type="button" onclick="loadDoc()">Get the AJAX data</button>

不需要CSS,将加载程序设置为不透明度0.3(以查看发生了什么),并且

JS

var output = ''; // the variable to hold the parsed response
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {


// so far ok, the trouble starts here, setting the loader to opacity 1
  document.getElementById("loader").style.opacity = 1;
  var theResponse = this.responseText;
  var parsedResponse = JSON.parse(theResponse); 
  // the looping through the data
  for (i=0; i < parsedResponse.length; i++ ) {
  output += '<li>' + parsedResponse[i].title +'</li>' + '<img src=' + 
  parsedResponse[i].thumbnailUrl + '/>'  + '<span>' + parsedResponse[i].url 
  + '</span>';
  };
  // here the response goes to the demo div.
  document.getElementById("demo").innerHTML = output;
  }
  // these 2 lines do not work as desired
  document.getElementById("loader").style.display = "none";
  document.getElementById("demo").style.display = "block";
  };
  xhttp.open("GET", "https://jsonplaceholder.typicode.com/photos", true);
  xhttp.send();
   }

我知道,这是一个异步请求,问题就在这里。

现在发生了什么,在解析按钮时,只要单击按钮,演示div就会动画到屏幕上,并且不会显示加载程序。

我使用的是大型数据集,请求和解析需要几秒钟。

有没有办法使这项工作有效,或者我是否必须将一些代码包装到setTimeout中?

codepen在这里,我很抱歉加载数据所花费的时间(对我来说是5秒)。

https://codepen.io/damPop/pen/gQOVEe?editors=0010

0 个答案:

没有答案