开发者

What's a good way to display a loading image until an ajax query completes?

开发者 https://www.devze.com 2023-01-20 00:53 出处:网络
Right now it contacts the server every time a user toggles \"Comments (X)\" I\'d like to make it so as soon as a user clicks \".info .reply\" (Comments (X)), an ajax loader appears just until the dat

Right now it contacts the server every time a user toggles "Comments (X)"

I'd like to make it so as soon as a user clicks ".info .reply" (Comments (X)), an ajax loader appears just until the data is finished loading, then the loader disappears.

// Replies - Toggle display of comments
$('.info .reply').click( function() {
    $('.reply', this.parentNode.parentNode).toggle();
    return false;
});

// Load comments
$('.info .reply', this).mousedown( function() {
    var id = $('form #id', this.parentNode.parentNode).val();
    $.ajax({ url: location.href, type: 'post', data: 'id=' + id, dataType: 'json',
        success: function(data) {
            for (var i in data) {
                // Do AJAX Updates
            开发者_如何学C}
        }
    });
    return false;
});

What's the proper way to do this?

Thanks!


Basically

Show the image on mousedown using show() or fadeIn() or whatever tickles your fancy, then hide it inside your success callback. Like this

$('.info .reply', this).mousedown( function() {
    $("#loading-image").show(); // Show the progress indicator
    var id = $('form #id', this.parentNode.parentNode).val();
    $.ajax({ url: location.href, type: 'post', data: 'id=' + id, dataType: 'json',
        success: function(data) {
            $("#loading-image").hide(); // Hide the progress indicator
            for (var i in data) {
                // Do AJAX Updates
            }
        }
    });
    return false;
});


You can use a plugin such as jQuery BlockUI to do this. Just call $.blockUI() before calling $.ajax. Then at the end of the success event, call $.unblockUI().

0

精彩评论

暂无评论...
验证码 换一张
取 消