初始化后如何覆盖jQuery.ajax成功函数? [英] How to override the jQuery.ajax success function after it has been initialized?

查看:71
本文介绍了初始化后如何覆盖jQuery.ajax成功函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

单击按钮会触发ajax请求.当用户在第一个请求仍在加载时再次单击该按钮时,我想用另一个请求来覆盖第一个请求的成功功能.

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 function with another one.

基本上我想这样做:

var ajaxRequest = null;

jQuery('#mybutton').click(function () {
    if (ajaxRequest) {
        ajaxRequest.success = function () {
        };
    }

    ajaxRequest = jQuery.ajax({
        url: '...',
        success: function () {
            console.debug('do something');
        }
    });
});

但是最初的成功处理程序被调用. 如何实现覆盖?

But the initial success handler is been called. How to achieve an override?

推荐答案

您可以先将ajax参数设置为变量,以便稍后进行修改.

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);
});

如果只想在ajax仍在加载时修改成功函数,则可以执行以下操作:

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);
    }
});

这篇关于初始化后如何覆盖jQuery.ajax成功函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆