Show/hide html element on javascript xhr request function

旧巷老猫 提交于 2019-12-11 09:48:13

问题


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


来源:https://stackoverflow.com/questions/10563448/show-hide-html-element-on-javascript-xhr-request-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!