Javascript 正在进行 AJAX 调用时显示“正在加载”图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7082323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:46:30  来源:igfitidea点击:

Display 'loading' image when AJAX call is in progress

javascriptjqueryajax

提问by Or Weinberger

I have the following jQuery Ajax call:

我有以下 jQuery Ajax 调用:

$.ajax({
                   type: "POST",
                   url: "addtobasket.php",
                   data: "sid=<?= $sid ?>&itemid=" + itemid + "&boxsize=" + boxsize + "&ext=" + extraval,
                   success: function(msg){
                     $.post("preorderbasket.php", { sid: "<?= $sid ?>", type: "pre" },
                     function(data){
                        $('.preorder').empty();
                         $('.preorder').append(data); 
                     }); 
                   }
                 });

I want to display an image when the ajax call is in progress. How can I do that?

我想在 ajax 调用正在进行时显示图像。我怎样才能做到这一点?

Thanks,

谢谢,

回答by DonSeba

try this :

尝试这个 :

<script type="text/javascript">
    $(document).ready(function()
    {
        $('#loading')
            .hide()
            .ajaxStart(function() {
                $(this).show();
            })
            .ajaxStop(function() {
                $(this).hide();
            });
    });
</script>

<div id="loading">
        Loading....
</div>

This will show the loading image each time you are doing an ajax request, I have implented this div at the top of my pages, so it does not obstruct with the page, but you can always see when an ajax call is going on.

这将在您每次执行 ajax 请求时显示加载图像,我在页面顶部实施了此 div,因此它不会阻碍页面,但是您始终可以看到 ajax 调用何时进行。

回答by Lobstrosity

Something along these lines (showLoadingImageand hideLoadingImageare up to you):

这些方针的东西(showLoadingImagehideLoadingImage是由你):

// show the loading image before calling ajax.
showLoadingImage();

$.ajax({
    // url, type, etc. go here
    success: function() {
        // handle success. this only fires if the call was successful.
    },
    error: function() {
        // handle error. this only fires if the call was unsuccessful.
    },
    complete: function() {
        // no matter the result, complete will fire, so it's a good place
        // to do the non-conditional stuff, like hiding a loading image.

        hideLoadingImage();
    }
});

回答by jeremyasnyder

You can display the image just before this call to $.ajax() and then hide/remove the image in the post handler function (just before your .empty()/.append(data) calls.

您可以在调用 $.ajax() 之前显示图像,然后在后处理函数中隐藏/删除图像(就在 .empty()/.append(data) 调用之前)。