gpt4 book ai didi

javascript - 为什么这个函数不等到它有来自 XHR 请求的数据?

转载 作者:搜寻专家 更新时间:2023-11-01 04:49:01 25 4
gpt4 key购买 nike

当我调用 getCurrentConditions 时,它会尝试在 requestData 完成之前返回数据,因此找不到 data.currently。我肯定从 URL 获取返回的数据,我尝试添加一个超时循环来等待 XHR 加载,但这只是一起破坏了脚本。我有点困惑为什么第二个函数不等待 this.requestData(latitude, longitude);在继续之前完成。

this.requestData = function(latitude, longitude) {
request_url = self.API_ENDPOINT + api_key + '/' + latitude + ',' + longitude + '?units=auto';
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState==4 && xhr.status==200) {
content = xhr.responseText;
if(content != '' && (content)) {
return JSON.parse(content);
} else {
return false;
}
}
}
xhr.open('GET', 'proxy.php?url='+request_url, true);
xhr.send(null);
}
/**
* Will return the current conditions
*
* @param float $latitude
* @param float $longitude
* @return \ForecastIOConditions|boolean
*/
this.getCurrentConditions = function(latitude, longitude) {
data = this.requestData(latitude, longitude);
if(data !== false) {
return new ForecastIOConditions(data.currently);
} else {
return false;
}
}



var forecast = new ForecastIO(api_key);
var condition = forecast.getCurrentConditions(latitude, longitude);

最佳答案

因为 ajax 是异步的,意味着一旦发送请求,它将继续执行而不等待响应。

一个简单的解决方案是通过将第三个参数传递给 .open() 来关闭异步特性。方法为 false,但它有缺点,如浏览器线程将被阻塞,直到请求完成,这意味着 UI 将保持无响应,直到请求完成。

xhr.open('GET', 'proxy.php?url='+request_url, false);

正确的解决方案是使用回调方法

this.requestData = function(latitude, longitude, callback) {
request_url = self.API_ENDPOINT + api_key + '/' + latitude + ',' + longitude + '?units=auto';
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState==4 && xhr.status==200) {
content = xhr.responseText;
if(content != '' && (content)) {
callback(JSON.parse(content));
} else {
callback(false);
}
}
}
xhr.open('GET', 'proxy.php?url='+request_url, true);
xhr.send(null);
}
/**
* Will return the current conditions
*
* @param float $latitude
* @param float $longitude
* @return \ForecastIOConditions|boolean
*/
this.getCurrentConditions = function(latitude, longitude, callback) {
this.requestData(latitude, longitude, function(data) {
if(data !== false) {
callback(ForecastIOConditions(data.currently));
} else {
callback(false);
}
});
}



var forecast = new ForecastIO(api_key);
forecast.getCurrentConditions(latitude, longitude, function(condition){
if(condition !== false) {

} else {

}
});

关于javascript - 为什么这个函数不等到它有来自 XHR 请求的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16080655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com