【发布时间】:2015-05-31 05:39:03
【问题描述】:
我试图在 XMLHttpRequest 获取请求之后返回一个 json 对象,但我做不到。我认为这可能是因为它是异步的,但我真的不知道如何使它工作。我做错了什么?
$(document).ready(function() {
var apiEndpoint = 'http://someapiendpoint.com/'
//Helpers
function sendRequest(_path) {
var results = {}
req = new XMLHttpRequest()
req.open('GET', apiEndpoint+_path)
req.onreadystatechange = function() {
if (this.readyState === 4) {
results = JSON.parse(this.response)
}
}
req.send()
return results
}
// Action
console.log(sendRequest('client1/'))
}); // end document ready
【问题讨论】:
-
异步调用伙伴,console.log只会得到你
{} -
嗯好吧,所以如果我这样做
req.open('GET', apiEndpoint+_path, false)它可以工作......但我想这也会阻止执行,对吧? -
你正在尝试返回尚未准备好的结果
标签: javascript jquery json xmlhttprequest