Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么这个函数不等待XHR请求中的数据?_Javascript - Fatal编程技术网

Javascript 为什么这个函数不等待XHR请求中的数据?

Javascript 为什么这个函数不等待XHR请求中的数据?,javascript,Javascript,当我调用getCurrentConditions时,它试图在requestData完成之前返回数据,因此找不到data.Current。我确实从URL返回了数据,我尝试添加了一个超时循环来等待XHR加载,但这只是破坏了整个脚本。我有点困惑为什么第二个函数不等待这个;在继续之前完成 this.requestData = function(latitude, longitude) { request_url = self.API_ENDPOINT + api_key + '/' + lati

当我调用getCurrentConditions时,它试图在requestData完成之前返回数据,因此找不到data.Current。我确实从URL返回了数据,我尝试添加了一个超时循环来等待XHR加载,但这只是破坏了整个脚本。我有点困惑为什么第二个函数不等待这个;在继续之前完成

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);

在此处放置
false
而不是
true

// `false` makes the request synchronous
xhr.open('GET', 'proxy.php?url='+request_url, false);
这使得调用是同步的,而不是异步的。因此,当调用变得同步时,它会等待ajax调用完成,然后执行所需的函数


XMLHttpRequest的Mozila链接:

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

一个简单的解决方案是通过将第三个参数作为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 {

    }
});

这是异步调用。尝试使用回调函数。 下面的代码是一个示例。没有测试

 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 {
                    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) {
        this.requestData(latitude, longitude, callback);        
    }

this.callback = function(data) {
if(data !== false) {
            return new ForecastIOConditions(data.currently);
        } else {
            return false;
        }
};
而不是

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


关于方法:

open(method,url,async)  
指定请求的类型、URL以及是否应异步处理请求

方法:
请求类型:GET或POST

url:
文件在服务器上的位置

async:
true(异步)或false(同步)


来源:w3schools

与Yes完全相同,它看起来未经测试,传播回调样式时未命中。您仍然
return
ing。别忘了提到更好的解决方案!别忘了建议不要使用sjax!主线程上的同步XMLHttpRequest不推荐使用,因为它会对最终用户的体验产生有害影响。如需更多帮助,请查看。
open(method,url,async)