我可以在控制台中看到对象的字段变量,但无法访问它

I can see the object's field variable in the console but cannot access it

我可以在控制台中看到对象的字段变量,但无法通过 objectName.fieldVariableName

访问它
var ob = jQuery.get("file.txt");
console.log("This is the resulting object");
console.log(ob);
console.log("This is the responseText");
console.log(ob.responseText);

当我尝试访问中的响应文本时,显示它未定义。但是,当我打印整个对象时,我可以看到正确的响应文本。如何访问 responseText 字段变量?

由于jQuery.get是一个异步方法,你需要提供一个回调函数,一旦请求成功就会被调用:

var ob = jQuery.get("file.txt", function(responseText)
{
    console.log("This is a jqXHR object");
    console.log(ob);
    console.log("This is the responseText");
    console.log(responseText);
});

jQuery 以响应数据作为第一个参数调用回调函数(上面代码中的responseText)。

您在控制台中看到 responseText 的原因可能是因为当您展开对象详细信息时,请求已经成功并且设置了 reponseText 字段。

另外,请注意 ob 不是 结果对象,而是 jqXHR 对象。

这是因为您需要使用回调函数来处理您的 get 请求的 success 事件。

$.get("file.txt", function(data) {
    console.log(data);
});

当您在控制台中执行它时,请求已完成并填充了对象。但是,在您的代码片段中,请求在执行时尚未完成。

有关详细信息,请参阅 jQuery.get