2017-03-17 67 views
0

我们希望在点击提交按钮后立即显示gif加载消息,并在数据加载完成后立即消失。。为什么?

到目前为止它还没有很好地工作。

只要页面加载,但点击提交按钮之前,GIF加载器显示,并保持显示,即使数据完成加载。

我该如何解决这个问题?

$("#btnSubmit").click(function (event) { 
     event.preventDefault(); 
    if (confirm('Please verify that your information is correct before submitting.')) { 
    var empComplete = false, sourceComplete = false, spouseComplete = false, dividentComplete = false, reimbursedComplete = false, honorariaComplete = false, giftComplete = false, orgComplete = false, creditorComplete = false; 
    function checkComplete() { 
    if (empComplete && sourceComplete && spouseComplete && dividentComplete && reimbursedComplete && honorariaComplete && giftComplete && orgComplete && creditorComplete) { 
    $("#result").text("Thank you! You have successfully completed this form"); 
    } 
    } 

//Loading message handler 
    var $loading = $('#loadingDiv').hide(); 
    $(document) 
    .ajaxStart(function() { 
    $loading.show(); 
    }) 
    .ajaxStop(function() { 
    $loading.hide(); 
    }); 

    $("#result").text(""); 
    var data = JSON.stringify(getAllEmpData()); 
    console.log(data); 
    $.ajax({ 
    url: 'disclosures.aspx/SaveEmpData', 
    type: 'POST', 
    contentType: 'application/json; charset=utf-8', 
    data: JSON.stringify({ 'empdata': data }), 
    async: false, 
    success: function() { 
    empComplete = true; 
    checkComplete(); 
    }, 
    error: function() { 
    alert("Error while inserting data"); 
    } 
    }); 
    } 
    )}; 
    ... 
    ... 
    </script> 

    //Markup 

    <input type="submit" id="btnSubmit" class="btn btn-primary btn-md pull-center btn-sm" value="Submit" /><img id="loadingDiv" src="images/ajax-loader.gif" alt="Loading..." /> 
    <output id="result" style="margin-bottom:300px;margin-left:250px;color:#3c890e;font-weight:bold;font-size:18px;"></output> 
+0

你能提供html吗? – Nicholas

+0

@Nicholas,它位于提交按钮旁边的底部。 谢谢你的回应。 – Kenny

回答

1

只要放上'display:none;'到img开始:

<img id="loadingDiv" style="display:none;" src="images/ajax-loader.gif" alt="Loading..." /> 

或将其隐藏在文档上准备就绪。

也隐藏加载gif,隐藏它在你的成功和错误功能或'完成'。

ajaxStop从jQuery文档中检查页面上的所有ajax请求,而不仅仅是您正在制作的所有ajax请求: 注册处理程序以在所有Ajax请求完成时调用。

另外,不要在'success'或'error'或'complete'函数中使用它们,它们是异步的,变量将超出范围,除非您将它传入。只需再次使用jquery选择div 。

+0

感谢您的帮助@Martina。 – Kenny