displaying a spinner when we make an ajax call and waiting for the response and blocking the page

偶尔善良 提交于 2019-12-13 00:52:58

问题


I have a page with multiple ajax call to load a part from the response ...Now I have to show a spinner on the part from which I am making an ajax call waiting for the content to get loaded...How can I have a common method which will take a parameter as a selector for the part from which I am making an ajax call and blocking the page background

thank for any suggestion and help.


回答1:


my code for that:

$.fn.ajaxConvertLink = function() {
    $(this).click(function() {
        var wrap = $(this).parent();
        if (!wrap.hasClass('spinner')) {
            wrap.addClass('spinner');
            $.ajax({
                type: 'GET',
                url: $(this).attr('href'),
                success: function(data) {
                    $('#content_for_layout').html(data);
                },
                complete: function() {
                    wrap.removeClass('spinner');
                }
            });
        }
        return false;
    });
};

it adds class spinner (which in css is described with a background spinner image) to parent element (but can be easly changed to alter a itself or completely other element)

<a href="/foo/bar" id="xxx'>YYY</a>

execute:

$('#xxx').ajaxConvertLink();

http://jsfiddle.net/Jacek_FH/2dAyf/




回答2:


You could write a proxy around the jQuery.ajax method. We'll add some simple markup (that you can style elsewhere) to the elements whose contents are being loaded, then replace that markup with the responseText once the request has completed:

jQuery.fn.extend({

    // usage: $(<selector>).spinnerload(); 
    spinnerload: function(url, options)
    {   
        var self = this;
        var options = options || {};
        var success = options.success || function() {};

        options.success = function(responseText, status, jqXHR)
        {
            self.html(responseText);
            success(responseText, status, jqXHR);
        }

        self.html('<div class="loading"></div>');
        jQuery.ajax(url, options);
    }

});


来源:https://stackoverflow.com/questions/7003339/displaying-a-spinner-when-we-make-an-ajax-call-and-waiting-for-the-response-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!