显示/隐藏loading gif

时间:2019-01-27 21:12:43

标签: jquery ajax

我要执行的操作是,一旦在表单上按下按钮,就会在按钮旁边显示一个加载的gif文件,直到加载.php文件为止。

我的代码可以正常工作,一旦按下按钮,“ loading.gif”就会在按钮旁边出现,唯一的是,一旦.php文件中的数据输出到我想要的屏幕上要禁用加载gif,我想不出最好的方法。

        <div class="panel panel-primary">
            <div class="panel-heading">Display any backlinks for the current domain / url.</div>
            <div class="panel-body">

                    <form action="backlinks.php" id="backlinksForm" method="post" class="form-horizontal container-fluid" role="form">

                        <div class="row form-group">
                            <div class="col-sm-4 text-right"><label for="" class="control-label">Domain / URL: <a href="" data-toggle="tooltip" title="This is the URL / Page we will return the backlinks for"><span class="glyphicon glyphicon-question-sign"></span></a></label></div>
                            <div class="col-sm-8"><input class="form-control" type="text" id="backlink_url" name="backlink_url" value="" required="required" size="50" /></div>
                        </div>                  

                        <div class="row form-group">
                            <div class="col-sm-12 text-right">
                                <button type="submit" name="getBacklinks" class="btn btn-primary"><img id="imgLoading" class="hidden" src="images/loading.gif" alt="Loading..." />&nbsp;Source Backlinks</button>
                            </div>
                        </div>  

                    </form>
            </div>
            <div class="panel-footer">Enter your target URL and hit <b>Get Backlinks</b>!</div>
        </div>
        <div id="mainContent"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>        
<script>
$(document).ready(function(){
    $('#backlinksForm').on('submit', function(e){
        $('#imgLoading').removeClass('hidden');
        // Stop the form from submitting itself to the server.
        e.preventDefault();
        var backlink_url = $('#backlink_url').val();
        $.ajax({
            type: "POST",
            url: 'ajax-backlinks.php',
            data: {backlink_url: backlink_url, backlink_user_id: <?php echo $globId; ?>},
            success: function(data) {
                $('#mainContent').html(data);
            }
        });
    });
});
</script>

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

一旦AJAX调用成功,您可以将imgLoading类重置为隐藏状态,如下所示:

$.ajax({
        type: "POST",
        url: 'ajax-backlinks.php',
        data: {backlink_url: backlink_url, backlink_user_id: <?php echo $globId; ?>},
        success: function(data) {
            $('#mainContent').html(data);
            $('#imgLoading').addClass('hidden'); //Hides the loading gif after main content is loaded
        }
    });