How to override the jQuery.ajax success function after it has been initialized?

前端 未结 3 1238
不知归路
不知归路 2021-01-21 22:55

A button click triggers an ajax request. When the user clicks the button a second time while the first request is still loading, i want to override the first request\'s success

3条回答
  •  后悔当初
    2021-01-21 23:07

    Nice question , this will work..

    var isRequestDone = true;
    
    jQuery('#mybutton').click(function () {
        var requestParams = {
            url: '....',
            beforeSend: function () {
                isRequestDone = false;
            },
            success: function () {
                isRequestDone = true;
                console.debug('do something');
            },
            error: function () {
                isRequestDone = true;
            }
        }
        if (!isRequestDone) {
            requestParams.success = function () {
                console.log('please wait for a while!'); 
            };
        }
    
        jQuery.ajax(requestParams);
    });
    

    beforeSend will fire just before the request will go to server , so when request in on the server isRequestDone will be false and hence will change success handler . on success callback from the first request it will again back to original.

提交回复
热议问题