Show/hide html element on javascript xhr request f

2019-07-25 07:32发布

问题:

i have a signle html element which i need to show and hide by jquery into a pure javascript xhr request method, for now it shows always the element without hiding when request is complete/success, on error i would like to hide that again.

html

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

xhr method

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();
  };
}

the problem is that i always do that by $.ajax() statements(error,success,beforeSend), this time i have pure javascript xhr requests and i don't know how to do that.

to be more clear i would like this converted to xhr javascript as shown:

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

EDITED

i tryed also without success:

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);
  };
}

回答1:

Check this one: Wiki for xmlhttprequest

In the xmlHTTPRequest you have to check the state of the object to find out what is going on with the request.



回答2:

fixed with

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

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