【问题标题】:How to return True or False from function using Jquery asynchronous Ajax call [duplicate]如何使用 Jquery 异步 Ajax 调用从函数中返回 True 或 False [重复]
【发布时间】:2016-03-15 08:29:18
【问题描述】:

我希望以下函数根据我的逻辑返回真或假,但函数返回未定义。

function getUserData() {
    $.ajax({
    type: 'POST',
    contentType: 'application/json',
    url: 'myservice',
    dataType: "JSON",
    success: function (data) {
        if (data.d.UserID > 0) {
            return true;
        } else {
            return false
        }
        return false;
    },
    error: function (error) {
        return false;
    }
});};
if (getUserData()) {
//do something
} else {
//redirect
}

请不要认为它是重复的,它是不同的,我不想返回回调函数我想根据那些回调函数返回true或false。

【问题讨论】:

  • 请输入您从哪里获取数据的操作代码,或者至少向我们展示您从服务器获得的输出/响应。
  • 服务器运行良好并返回我的数据,但我无法将这些 true 或 false 返回给 getUserData()
  • 是的,你是对的。但我想在这个函数中决定我的逻辑,不想到处重复我的逻辑
  • 它是异步的,因此根据定义,在完成之前您无法取回结果。这就是 重复问题 深入解释的内容:stackoverflow.com/a/14220323/2181514
  • 不清楚为什么你认为你需要“在任何地方重复逻辑”——这就是回调函数的用途——你将逻辑函数传递给 ajax 包装器。此处在副本中进行了解释:“回调将引用我们在调用时传递给 foo 的函数,我们只需将其传递给成功”

标签: jquery ajax asynchronous promise


【解决方案1】:

试试这个:

function getUserData(callback) {
    $.ajax({
        type: 'POST',
        contentType: 'application/json',
        url: 'myservice',
        dataType: "JSON",
        success: function (data) {
            if (data.d.UserID > 0) {
                callback(true);
            } else {
                callback(false);
            }
            callback(false);
        },
        error: function (error) {
            callback(false);
        }
    });
};

getUserData(function(status) {
    if (status) {
    //do something
    } else {
    //redirect
    }
});

【讨论】:

  • 我试试 谢谢,会尽快发布我的反馈
  • 应该 callback(true) 是 callback = true
  • 没用,但还是感谢您抽出宝贵时间
  • 什么不起作用?您没有将status 值设为真/假吗?
  • 是的控制台说状态不是一个函数,顺便说一句,我已经从你的代码中更改了我的代码,所以不能再向你显示控制台详细信息
【解决方案2】:

使用以下代码可能会解决您的问题:创建一个函数,它应该返回延迟对象。

  function AJAX(type,url){

   this.type=type;      // EX: GET , POST
   this.url=url;

this.invoke = function(){
var deferred = $.Deferred();
$.ajax({
    type: this.type,
    url: this.url,      
    contentType: 'application/json',
    dataType:"JSON"
    success: function(response){
        deferred.resolve(response);
    },
    error: function(exception){
        console.log("Ajax call returned error.");
         deferred.reject(exception);
    }
});

return deferred;

};
}

现在用正确的参数调用这个函数,如下所示

 var ajax=new AJAX("POST","Your action");
 ajax.invoke().then(function(data){
       if(data==true){
         // Your code for true
          }else{
         // your code for false
         }
  });

现在您可以根据需要修改功能..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-29
    • 2015-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多