为什么我的jqxhr.responseText变量未定义,当它在xhr对象中设置时?

ear*_*efl 5 coldfusion jquery

我在这里有一个真正简单的jquery get调用,我想稍后在脚本中使用响应.所以,如果我这样做:

var xhr = $.get('cfc/partsDefinition.cfc',{
                method: 'checkValid',
                search: 'some search string'
            }
        );
        console.log(xhr);
        console.log(xhr.responseText);
Run Code Online (Sandbox Code Playgroud)

我可以看到A)第一个日志显示一个有效的jqxhr对象,responseText属性设置为我期望的...

promise: function (a){if(a==null)a=h;else for(var b in h)a[b]=h[b];return a}
readyState: 4
responseText: "0"
setRequestHeader: function (a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this}
Run Code Online (Sandbox Code Playgroud)

但是B)第二个日志显示"未定义".我在这里错过了什么?

use*_*654 4

它之所以显示是undefined因为在代码中的那个点,它是未定义的。AJAX 是异步的,这意味着它不会在代码运行之前完成。responseText在 ajax 调用完成之前, 是未定义的。这是一个例子:

var xhr = $.get('cfc/partsDefinition.cfc',{
                method: 'checkValid',
                search: 'some search string'
            }
        ).done(function(data){
            console.log("xhr",xhr);
            console.log("xhr.responseText",xhr.responseText);
            console.log("data",data);
        });
console.log("This should happen before the other console logs");
Run Code Online (Sandbox Code Playgroud)