Adding a loading image to a jquery ajax post

时光毁灭记忆、已成空白 提交于 2019-12-04 10:17:39

Just add a few calls to hide/show your load screen/div, whatever:

<script type="text/javascript">
    $(function() {
        $('#contact form').live('submit', function() {
            $("#Loading").fadeIn(); //show when submitting
            $.post($(this).attr('action'), $(this).serialize(), function(data) {
                $("#contact").replaceWith($(data));
                $("#Loading").fadeOut('fast'); //hide when data's ready
            });
            return false;
        });
    });
</script>

<div id="Loading">I'm loading, image here, whatever you want</div>
Mark Schultheiss

I put this in so that is shows on every ajax call, no matter which one I have (I have several)

/* show the message that data is loading on every ajax call */
var loadingMessage = 'Please wait loading data for ' + defaultPageDoctor;
$(function()
{
    $("#Errorstatus")
    .bind("ajaxSend", function()
        {
            $(this).text(loadingMessage);
            $(this).show();
        })
    .bind("ajaxComplete", function()
    {
        $(this).hide();
    });
});

Just create an element with the #ErrorStatus id such as:

<div class="newProcedureErrorStatus ajaxLoading " id="newProcedureErrorStatus">
    <span id="Errorstatus" class="ui-state-error-text newProcedureErrorStatusText"></span>
    <span id="Errorstatus2" class="ui-state-error-text newProcedureErrorStatusText">
    </span>
</div>

Now for the bonus rounds, you can use this area to put other messages up, I also include a timer:

/* show message for interval */
var saveMessageText = 'Saving...';
function ShowStatus(saveMessage, message, timeInMilliseconds)
{
    var errorMessage = $("#Errorstatus");
    if (saveMessage)
    {
        errorMessage.show();
        //var myNumber = 0;
        var myInterval = window.setInterval(function()
        {
            message = message + '...';
            errorMessage.text(message);
            errorMessage.show();
        }, 1000);
        window.setTimeout(function()
        {
            clearInterval(myInterval);
            errorMessage.hide();
        }, timeInMilliseconds);
    }
    else
    {
        errorMessage.text(message);
        errorMessage.show();
        window.setTimeout('$("#Errorstatus").hide()', timeInMilliseconds);
    };
};

use it like so:

 ShowStatus(true, 'Save Failed with unknown Error', 4000);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!