在javascript xhr请求函数上显示/隐藏html元素

Show/hide html element on javascript xhr request function

本文关键字:隐藏 html 元素 显示 javascript xhr 请求 函数      更新时间:2023-09-26

我有一个 signle html 元素,我需要通过 jquery 在纯 JavaScript xhr 请求方法中显示和隐藏它,现在它总是显示元素而不隐藏请求完成/成功,如果出错我想再次隐藏它。

.html

<div class="ajax-loading">Loading ..</a>

XHR 方法

function post(_url, _callback,_data){
  var xhr = createCORSRequest('POST',_url);
  if (!xhr){
    throw new Error('CORS not supported');
  }
  $('.ajax-loading').show();
  xhr.send(_data);
  /*SUCCESS -- do somenthing with data*/
  xhr.onload = function(){
    // process the response.
    _callback(xhr.responseText);
    $('.ajax-loading').hide();
  };
  xhr.onerror = function(e){
    console.log(e);
    $('.ajax-loading').show();
  };
}

问题是我总是通过$.ajax()语句(error,success,beforeSend)来做到这一点,这次我有纯粹的JavaScript XHR请求,我不知道该怎么做。

为了更清楚,我希望将其转换为XHR JavaScript,如下所示:

$.ajax({
/*data etc ...*/
error:function(){
$('.ajax-loading').show();
},
success:function(){
$('.ajax-loading').hide();
},
beforeSend:function(){
$('.ajax-loading').show();
}
});

编辑

我也尝试过但没有成功:

function get(_url, _callback){
  var xhr = createCORSRequest('GET',_url);
  if (!xhr){
    throw new Error('CORS not supported');
  }

  xhr.send();
  xhr.onreadystatechange = function() {
        if(xhr.readyState == 4 /*COMPLETE STATEMENT*/){
            alert(xhr.readyState);
        }
};
  /*SUCCESS -- do somenthing with data*/
  xhr.onload = function(){
    // process the response.
    _callback(xhr.responseText);
  };
  xhr.onerror = function(e){
    console.log(e);
  };
}

检查这个:Wiki for xmlhttprequest

在xmlHTTPRequest中,你必须检查对象的状态,以了解请求发生了什么。

固定

xhr.onloadstart = function(){
       $('.ajax-loading').show();
  }
  xhr.onloadend = function(){
      $('.ajax-loading').hide();
  }