当AJAX调用正在进行时显示"加载"图像

Or *_*ger 9 javascript ajax jquery

我有以下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); 
                     }); 
                   }
                 });
Run Code Online (Sandbox Code Playgroud)

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

谢谢,

Don*_*eba 27

试试这个 :

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

<div id="loading">
        Loading....
</div>
Run Code Online (Sandbox Code Playgroud)

这将显示每次执行ajax请求时的加载图像,我已经在页面顶部实现了这个div,因此它不会阻碍页面,但是你总能看到ajax调用何时进行.

  • 请注意,这将显示*any*ajax请求正在进行时的加载div. (3认同)

Lob*_*ity 5

这些方针的东西(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();
    }
});
Run Code Online (Sandbox Code Playgroud)

  • ajax对象中还有一个beforeSend参数 (4认同)