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

前端 未结 3 1241
不知归路
不知归路 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:05

    You can set the ajax arguments to a variable first so you can modify it later on.

    var clicks = 0,
        ajaxArgs = {
            url: '...',
            success: function () {
                console.debug('do something');
            }
        };
    
    
    $('#myButton').click(function() {
        ++clicks; 
        if (clicks > 1) {
            // set the success function if clicked more than once
            ajaxArgs.success = function () {
                console.debug('Success function ' + clicks);
            }
        }
    
        $.ajax(ajaxArgs);
    });
    

    If you want to modify the success function only when ajax is still loading you can do this:

    var loading = false,
        ajaxArgs = {
            url: '...',
            success: function () {
                console.debug('do something');
            }, complete: function () {
                loading = false;
            }
        };
    
    $('#myButton').click(function() {
        if (loading) {
            // set the success function if ajax is still loading
            ajaxArgs.success = function () {
                console.debug('Another Success function ');
            }
        } else {
            loading = true;
            $.ajax(ajaxArgs);
        }
    });
    

提交回复
热议问题