【问题标题】:Display 'loading' image when AJAX call is in progress当 AJAX 调用正在进行时显示“正在加载”图像
【发布时间】:2011-08-16 17:25:10
【问题描述】:

我有以下 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); 
                     }); 
                   }
                 });

我想在 ajax 调用进行时显示图像。我该怎么做?

谢谢,

【问题讨论】:

标签: javascript jquery ajax


【解决方案1】:

试试这个:

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

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

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

【讨论】:

  • 请注意,当 any ajax 请求正在进行时,这将显示加载 div。
【解决方案2】:

类似的事情(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();
    }
});

【讨论】:

  • ajax对象中还有一个beforeSend参数
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-04
    • 1970-01-01
    • 2018-01-12
    • 2011-06-08
    相关资源
    最近更新 更多