【问题标题】:Show loader while waiting asynchronous response在等待异步响应时显示加载器
【发布时间】:2017-04-18 15:32:11
【问题描述】:

我不知道如何在等待用 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和英文一样,所以我需要帮助,谢谢你们!

【问题讨论】:

    标签: javascript php ajax


    【解决方案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 只要您调用 Ajax 调用,并且 当就绪状态为 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
       }
    }
    

    【讨论】:

    • 这更准确,所以我认为它也可以帮助更好的其他人,为此我选择了这个答案为正确的。但是 MachProgramAlot 之一也是正确的。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2013-10-19
      • 2011-09-03
      • 1970-01-01
      • 1970-01-01
      • 2020-12-09
      • 2020-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多