[英]Cannot get the responseText out of Ajax request
我正在进行ajax调用并在响应中获取对象。
当我尝试获取responseText时,它告诉我它是未定义的:
var results = API.get('users', { username: un, userpass: pw } );
console.log(results); //the object response below
console.log(results.responseText); // returns undefined
对象看起来像(我删除了响应的无用部分):
Object {readyState: 1, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
responseJSON: Object
responseText: "{"orderBy":"","orderDesc":false,"rows":[{"id":"26","name":"Jordan Simon","username":"jordan","userpass":"jordan"}],"totalResults":1,"totalPages":1,"pageSize":1,"currentPage":1}"
statusText: "OK"
__proto__: Object
我究竟做错了什么? 你能举个例子吗?
您可以在评论中找到答案,但这是对发生的情况的完整解释:
API.get正在对某个服务器进行异步调用,这可能会或可能不会在将来的某个时间返回响应。 在API.get调用之后但返回响应之前立即执行console.log(results)时。
大多数AJAX调用允许您指定一个回调函数,该函数将在异步操作完成后立即执行。
例如在jQuery中:
$.get( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
alert( "Load was performed." );
});
该方法看起来像这样:
$.get(url, callback) {
//do some stuff here with the URL
//get the response text, get the XHR response, anything goes really
//execute the callback method passed by the user
callback(responseText);
//return XHR response
return ajaxResults;
}
注意$ .get方法中的第二个参数如何是一个函数。 这是异步AJAX调用的基础。
您的API可能有所不同,也许您需要注册一个事件,或者出于任何目的可以关闭异步。 查看您的API文档,祝您好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.