如何访问成功返回的jQuery jqxhr对象的属性

How to access properties of returned jQuery jqxhr object if returned from sucess()

本文关键字:jQuery jqxhr 对象 属性 返回 成功 何访问 访问      更新时间:2023-09-26

这似乎是最奇怪的事情:

var mah_dataz = $.get("link/to/request");
console.log(mah_dataz);
/* result is the whole shebang: 
  Object {
    abort: function (a){var b=a||u;return d&&d.abort(b),c(0,b),this}
    always: function (){return e.done(arguments).fail(arguments),this}
    complete: function (){if(i){var c=i.length;!function f(b){ab.each(b,function(b,c)
    readyState: 4
    ... you get the idea...
    responseText: "{'returns': {'wellFormatted':'JSON', 'cross':'MyHeart'}}" */

但是!

var mah_dataz = $.get("link/to/request");
console.log(mah_dataz.responseText)
// result is: 
// undefined

这个很快被标记为重复并被驳回,但没有人完全回答这个问题,更不用说发布一个链接到重复的问题了。问题是:

为什么是这样?为什么在第一种情况下返回整个对象,然后,在第二种情况下,当其属性被引用时,它是未定义的?我不明白为什么这种对象的行为从根本上(或似乎如此行为)不同于其他javascript对象?

不完全是。get返回一个延迟的而不是回调的结果

var mah_dataz;
var deferred = $.get("link/to/request", function(jqxhr_ob) { mah_dataz = jqxhr_ob});

如果你只是在响应之后,你可以做…

$.get("link/to/request")
    .done(function(response) {
        console.log(response);
    });

更整齐