简体   繁体   English

从ajax访问数据是否成功完成?

[英]Access data from ajax success in complete?

Is there a way that I can access the data I receive during success so i can use it during the complete callback? 有没有一种方法可以访问成功期间接收到的数据,以便可以在完整的回调期间使用它?

Or perhaps there is a way where i can assign multiple success functions? 也许有一种方法可以分配多个成功功能?

What i need is, to allow success callback to be changed based on situation, but I need to always perform a dedicated function on success using the same data that was returned to the first function. 我需要的是,允许根据情况更改成功回调,但是我需要始终在成功时使用返回到第一个函数的相同数据来执行专用功能。

I suppose i can always setup my call like so, but i'm looking to see if there is a better way. 我想我总是可以这样设置我的电话,但是我正在寻找是否有更好的方法。

CallServer = function(options) {
  if(options.success) {
    var customSuccess = options.success;
    options.success = function(data) {
      defaultSuccess(data);
      customSuccess(data);
    }
  }
  $.extend(true, defaults, options);
  $.ajax(defaults);
}

EDIT: I have found my answer. 编辑:我找到了答案。 I didn't realize that the xhr holds the data as the responseText. 我没有意识到xhr将数据保存为responseText。 so the following gets me the same thing that gets returned as 'data' on success. 因此,以下内容使我获得成功时作为“数据”返回的内容相同。

complete: function(xhr){dosomething(xhr.responseText);}

and that's it! 就是这样! Thanks 谢谢

In jQuery, the success callback accepts the data as its first argument. 在jQuery中,成功回调将数据作为其第一个参数。

From the jQuery Documentation ( http://api.jquery.com/jQuery.ajax/ ) the argument list for the success callback is: 根据jQuery文档( http://api.jquery.com/jQuery.ajax/ ),成功回调的参数列表为:

success(data, textStatus, jqXHR) 成功(数据,textStatus,jqXHR)

As far as I am aware, there is no built-in way to add multiple success callbacks, but you could easily dispatch any number of functions from a custom success callback. 据我所知,没有内置的方法可以添加多个成功回调,但是您可以轻松地从自定义成功回调中分派任意数量的函数。

Perhaps you could use a system like: 也许您可以使用类似以下的系统:

function customSuccess(data) {
    if (situation == "one way") {
        firstFunction(data):
    }
    else if (situation == "another way") {
        secondFunction(data);
    }
}

I have found my answer. 我找到了答案。 I didn't realize that the xhr holds the data as the responseText. 我没有意识到xhr将数据保存为responseText。 so the following gets me the same thing that gets returned as 'data' on success. 因此,以下内容使我获得成功时作为“数据”返回的内容相同。

complete: function(xhr){dosomething(xhr.responseText);}

and that's it! 就是这样! Thanks 谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM