简体   繁体   English

从$ .get请求访问jqXHR对象属性

[英]Accessing jqXHR object properties from $.get request

I have a simple function that looks like this: 我有一个简单的函数,看起来像这样:

function getURL(url) {
  return $.get(url);
}

Which im calling (somewhere else, specifically in a unit test) as such: 即时通讯这样调用(在其他地方,特别是在单元测试中):

var url = getURL("/page/stuff")
    console.log(url);

So console.log(url) works, and returns statustext/status etc... like it should. 因此console.log(url)可以正常工作,并返回statustext / status等。

However, how can I access the properties of the jqXHR object. 但是,如何访问jqXHR对象的属性。 For instance url.status returns undefined. 例如url.status返回undefined。

Is this a loading issue? 这是加载问题吗? Whereas im logging before i've truly received the page...if so how come printing off just the url variable returns the object? 而在我真正收到该页面之前正在记录日志...如果是这样,如何打印出仅url变量返回该对象?

how can I access the properties of the jqXHR object. 如何访问jqXHR对象的属性。 For instance url.status returns undefined. 例如url.status返回undefined。

By accessing it after the request has completed: 在请求完成后访问它:

var jqxhr = getURL("/page/stuff");

jqxhr.always(function (result) {
    console.log(jqxhr.status);
});

Is this a loading issue? 这是加载问题吗? Whereas im logging before i've truly received the page... 我在真正收到该页面之前正在记录日志...

Yes. 是。

if so how come printing off just the url variable returns the object? 如果是这样,如何打印出仅url变量返回对象?

Because $.get() returns an object that represents the request. 因为$.get()返回表示请求的对象。 But some of its properties are not populated until the request completes. 但是,在请求完成之前,不会填充其某些属性。

jQuery.get() is a jQuery promisse, so you have xhr options on the Deferred object. jQuery.get()jQuery允许对象,因此Deferred对象具有xhr选项。

I think you want this: 我想你想要这个:

var _request = function( url ) {
    return $.get( url );
};

_request('https://httpbin.org/get').done(function( data, textStatus, jqXHR ) {
    console.info( jqXHR.status );
});

More information here: https://api.jquery.com/jQuery.ajax/#jqXHR 此处的更多信息: https : //api.jquery.com/jQuery.ajax/#jqXHR

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

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