在javascript xhr请求函数上显示/隐藏html元素 [英] Show/hide html element on javascript xhr request function
问题描述
我有一个signle html元素,我需要通过jquery显示和隐藏到纯javascript xhr request方法中,现在,当请求完成/成功时,它始终显示该元素而不隐藏,出现错误时,我想将其隐藏再次.
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方法
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()语句(错误,成功,beforeSend)来执行此操作,这一次我有纯JavaScript xhr请求,但我不知道该怎么做.
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.
更清楚地说,我希望将其转换为xhr javascript,如下所示:
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();
}
});
已编辑
我尝试也没有成功:
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);
};
}
推荐答案
选中以下一项: 用于xmlhttprequest的Wiki
在xmlHTTPRequest中,您必须检查对象的状态以查明请求所发生的情况.
In the xmlHTTPRequest you have to check the state of the object to find out what is going on with the request.
这篇关于在javascript xhr请求函数上显示/隐藏html元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!