如何将接收到的值分配给作为 Web 服务器响应的“值”变量?
var value;
...
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
//alert(xhr.responseText);
var jsonResponse = JSON.parse(xhr.responseText);
value = jsonResponse.id;
//return value;
}
else {
console.error(xhr.statusText);
}
//return value;
};
...
您已经将响应中的参数分配给值变量。但看起来你的问题完全是另一回事。你正在发出一个异步请求,完整的看起来像这样:
请求在xhr.send()时刻发送,响应到达时xhr.onreadystatechange函数将工作。这什么时候会发生基本上是未知的。要使用来自响应的数据,您需要在应该使用值变量的回调函数中调用一个操作,如下所示: