2017-03-17 72 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