最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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 ments
$('.info .reply').click( function() {
    $('.reply', this.parentNode.parentNode).toggle();
    return false;
});

// Load ments
$('.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
            }
        }
    });
    return false;
});

What's the proper way to do this?

Thanks!

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 ments
$('.info .reply').click( function() {
    $('.reply', this.parentNode.parentNode).toggle();
    return false;
});

// Load ments
$('.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
            }
        }
    });
    return false;
});

What's the proper way to do this?

Thanks!

Share Improve this question asked Oct 16, 2010 at 0:58 ensnareensnare 42.2k67 gold badges168 silver badges230 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

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)

  1. 暂无评论