【问题标题】:how to call fail method into jquery.get/post success method?如何将失败方法调用到 jquery.get/post 成功方法中?
【发布时间】:2019-06-21 12:23:57
【问题描述】:

如何将失败方法调用为 ajax 回调成功方法?例如,当我从服务器获取一些日期时,我不得不说这些数据不正确。为此,我使用以下代码:

Loading.show();
$.post(_api_server+"sign/in.php",opt,function(gets){
    try{
            if(gets.success){  
                Toast.show("success!!!","succ"); 
            }else{ 
                // duplicate codes
                Loading.hide();
                Toast.show("not Ok!!!");
            }
    }catch(e){
        // duplicate codes
        Loading.hide();
        Toast.show("not Ok!!!");
    } 
}).fail(function(){
    // duplicate codes
    Loading.hide();
    Toast.show("not Ok!!!");
});

如您所见,我使用重复的代码来做一件事。我想使用这样的东西:

Loading.show();
$.post(_api_server+"sign/in.php",opt,function(gets){
    try{
            if(gets.success){  
                Toast.show("success!!!","succ"); 
            }else{ 
                this.fail();
            }
    }catch(e){
        this.fail();
    } 
}).fail(function(){
    Loading.hide();
    Toast.show("not Ok!!!");
});

我该怎么做?有什么办法吗?

--更新

我有很多带有不同失败方法的 ajax,我不能使用其他/外部函数。

【问题讨论】:

    标签: jquery ajax post get


    【解决方案1】:

    您可以简单地将重复的代码放在一个函数中。如果你将它定义为一个非匿名函数,或者你通过一个变量引用你的匿名函数,你将能够从任何地方调用它。

    
    var failedRequest = function(){
        Loading.hide();
        Toast.show("not Ok!!!");
    };
    
    Loading.show();
    $.post(_api_server+"sign/in.php",opt,function(gets){
        try{
                if(gets.success){  
                    Toast.show("success!!!","succ"); 
                }else{ 
                    failedRequest();
                }
        }catch(e){
            failedRequest();
        } 
    }).fail(failedRequest);
    

    【讨论】:

    • 嗨,谢谢你的回答,但我知道,我有很多 ajax 不同的失败方法,我不能用这个。
    • @saleh 你好!很抱歉不知道如何解决您的问题。我不确定是否可以从成功回调中调用失败方法。也许如果您没有找到替代方法(如果 jQuery API 没有以任何方式公开 fail 方法),您可以在变量中定义您的 fail 方法(不一定像我在答案中指定的那样)并从成功函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-06
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-16
    相关资源
    最近更新 更多