2017-04-18 34 views
0

我不知道如何显示加载程序,而我正在等待用JavaScript编写的函数响应。在等待异步响应时显示加载程序

我有一个<div>包含响应:

<input type="button" name="btn-s" value="Search"> 
<div align="center" id="div_feed_data"> 
</div> 

,并在同一页面中我调用该函数:

function get_feed_data(id_feed,not_add) 
{ 
    if (window.XMLHttpRequest) { 
    // code for IE7+, Firefox, Chrome, Opera, Safari 
    var xmlhttp=new XMLHttpRequest(); 
     } 
    else { 
    // code for IE6, IE5 
     var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
     xmlhttp.onreadystatechange=function() 
     { if (xmlhttp.readyState==4 && xmlhttp.status==200) 
     { 
    document.getElementById("div_feed_data").innerHTML=xmlhttp.responseText; //NELL' ELEMENTO CON QUESTO ID VIENE MOSTRATO IL RISULTATO MANDATO DAL SERVER 

    } 
    } 
     xmlhttp.open("GET","libraries/show_feed_data.php?id_feed="+id_feed+"&not_add="+not_add,true); 
     xmlhttp.send(); 
} 

现在我想打一个装载机GIF,而不是按钮,直到响应准备就绪,但我不知道该怎么办,因为我找到了纯Ajax代码的方法,而且我在英文中不擅长js,所以我需要帮助,谢谢各位!

回答

0

参见:http://fontawesome.io/examples/#animated

function get_feed_data(id_feed,not_add) 
{ 
    $('#myIcon').fadeIn(); 
    ... 
    ... 
    if (xmlhttp.readyState==4 && xmlhttp.status==200) 
    { 
     // request is complete 
     $('#myIcon').fadeOut(); 
    } 
    ... 
    ... 
} 
+0

是否OP说一下使用JavaScript框架参选?你怎么知道他使用的女巫框架?请用普通的javascript做这个或者请求使用的框架,thnx – JustOnUnderMillions

+0

它的工作,非常感谢你! –

+0

没问题@GiuseppeDePaola – MackProgramsAlot

1

当您创建一个Ajax请求,它会经过以下状态。

0: request not initialized 
1: server connection established 
2: request received 
3: processing request 
4: request finished and response is ready 

当您触发.send()方法时,将会处理这些状态。所以你试着显示装载机gif一旦你打电话给阿贾克斯调用和当准备状态是4时,你可以隐藏装载机。

伪代码

function yourFunction() { 
    //call the show loader function here 
    if(xmlReq.readyState == 4 && smlReq.status == 200){ 
     //call the hide loader function here 
    } 
} 

注意:您甚至还可以显示基于readyState值为每个状态的消息。

伪代码

function yourFunction() { 
    if(xmlReq.readyState == 1){ 
     //call the show loader function here 
     //console.log('connected'); 
    } 

    if(xmlReq.readyState == 2){ 
     //call the show loader function here 
     //console.log('Request Received'); 
    } 

    if(xmlReq.readyState == 3){ 
     //call the show loader function here 
     //console.log('Processing'); 
    } 

    if(xmlReq.readyState == 4 && xmlReq.status == 200){ 
     //call the hide loader function here 
    } 
} 
+1

这更准确,所以我认为它可以帮助更好的其他人,只是为了thati选择这个答案是正确的。但MachProgramAlot的一个也是正确的。 –